I am uploading & downloading files in bucket created on Google Cloud through Project created in Android-Studio.
I am feeling that images upload and download is taking long time.
I have also checked it by enabling automatic scaling, my appengine-web.xml file looks like:
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<application>APP_ID</application>
<version>1</version>
<threadsafe>true</threadsafe>
<instance-class>F4_1G</instance-class>
<automatic-scaling>
<min-idle-instances>1</min-idle-instances>
<!-- ‘automatic’ is the default value. -->
<max-idle-instances>automatic</max-idle-instances>
<!-- ‘automatic’ is the default value. -->
<min-pending-latency>30ms</min-pending-latency>
<max-pending-latency>automatic</max-pending-latency>
<max-concurrent-requests>50</max-concurrent-requests>
</automatic-scaling>
<system-properties>
<property name="java.util.logging.config.file" value="WEB-INF/logging.properties" />
<property name="gcm.api.key" value="gcm_key" />
</system-properties>
</appengine-web-app>
And Servlet to Upload image looks like this:
public class UploadImageServlet extends HttpServlet {
private static final Logger logger = Logger.getLogger(UploadImageServlet.class.getName());
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
ServletFileUpload upload = new ServletFileUpload();
resp.setContentType("text/plain");
FileItemIterator iterator = upload.getItemIterator(req);
ImageJson data = new ImageJson();
byte[] image = null;
byte[] imageThumbnail = null;
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream stream = item.openStream();
if (item.isFormField()) {
String field = item.getFieldName();
String value = IOUtils.toString(stream);
try {
if (field.equalsIgnoreCase(SESSION_PARAM_IN_FORM)) {
data.session = value;
} else if (field.equalsIgnoreCase(USER_PARAM_IN_FORM)) {
data.user = Long.parseLong(value);
}
} catch (NumberFormatException e) {
logger.warning("Invalid " + field);
}
// user, session
} else {
logger.info("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName());
data.imageName = item.getName();
// You now have the filename (item.getName() and the
// contents (which you can read from stream). Here we just
// print them back out to the servlet output stream, but you
// will probably want to do something more interesting (for
// example, wrap them in a Blob and commit them to the
// datastore).
image = IOUtils.toByteArray(stream);
System.out.println("Creating Thumbnail...");
ImagesService imagesService = ImagesServiceFactory.getImagesService();
Image oldImage = ImagesServiceFactory.makeImage(image);
Transform resize = ImagesServiceFactory.makeResize(120, 120);
//Resize The Image using the transform created above
Image resizedImage = imagesService.applyTransform(resize, oldImage);
imageThumbnail = resizedImage.getImageData();
System.out.println("Thumbnail created!!");
}
}
resp.getWriter().write(new Gson().toJson(saveImage(data, image, imageThumbnail)));
} catch (Exception ex) {
throw new ServletException(ex);
}
}
}
You must upload and download images using Json format.
If you want to know any more, please contact me
Hope will be helpfull
Related
Im investigating the use of citeproc in my current Android application
api 'de.undercouch:citeproc-java:2.0.0'
implementation 'org.citationstyles:styles:20.11'
implementation 'org.citationstyles:locales:20.11'
Its working fine using
// https://repo1.maven.org/maven2/com/eclipsesource/j2v8/j2v8/6.2.0/
implementation(name: 'j2v8-6.2.0', ext: 'aar')
However as Im running on Android OS the CSL static method
CSL.getSupportedStyles()
returns an empty list.
the underlying code in this method is as follows:-
private static Set<String> getAvailableFiles(String prefix,
String knownName, String extension) throws IOException {
Set<String> result = new LinkedHashSet<>();
// first load a file that is known to exist
String name = prefix + knownName + "." + extension;
URL knownUrl = CSL.class.getResource("/" + name);
if (knownUrl != null) {
String path = knownUrl.getPath();
// get the jar file containing the file
if (path.endsWith(".jar!/" + name)) {
String jarPath = path.substring(0, path.length() - name.length() - 2);
URI jarUri;
try {
jarUri = new URI(jarPath);
} catch (URISyntaxException e) {
// ignore
return result;
}
try (ZipFile zip = new ZipFile(new File(jarUri))) {
Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry e = entries.nextElement();
if (e.getName().endsWith("." + extension) &&
(prefix.isEmpty() || e.getName().startsWith(prefix))) {
result.add(e.getName().substring(
prefix.length(), e.getName().length() - 4));
}
}
}
}
}
return result;
}
Is it possible to list get getAvailableFiles method to work on Android OS?
The following aproach does not work
val name: String = "$prefix$knownName.$extension"
val knownUrl: URL? = CSL::class.java.classLoader.getResource("$name")
All I require is the list of ".csl" files that in an Eclipse java project show as residing in styles-20.11.jar file
When I extract my Application APK file the ".csl" files are all listed seperately
Where am I going wrong?
How can I get a list of all ".csl" files available to CSL?
Your provided detail guides me to find the solution. That's enough to define apk in the checker condition.
class CLSHelper {
public static Set<String> getSupportedStyles() throws IOException {
return getAvailableFiles("", "ieee", "csl");
}
/**
* Customizing this function to able run in Android environment
*/
private static Set<String> getAvailableFiles(String prefix,
String knownName, String extension) throws IOException {
Set<String> result = new LinkedHashSet<>();
// first load a file that is known to exist
String name = prefix + knownName + "." + extension;
URL knownUrl = CSL.class.getResource("/" + name);
if (knownUrl != null) {
String path = knownUrl.getPath();
// get the jar or apk file containing the file
if (path.endsWith(".jar!/" + name) || path.endsWith(".apk!/" + name)) { // changing this line
String jarPath = path.substring(0, path.length() - name.length() - 2);
URI jarUri;
try {
jarUri = new URI(jarPath);
} catch (URISyntaxException e) {
// ignore
return result;
}
try (ZipFile zip = new ZipFile(new File(jarUri))) {
Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry e = entries.nextElement();
if (e.getName().endsWith("." + extension) &&
(prefix.isEmpty() || e.getName().startsWith(prefix))) {
result.add(e.getName().substring(
prefix.length(), e.getName().length() - 4));
}
}
}
}
}
return result;
}
}
Output:
CSL.getSupportedStyles() // []
CLSHelper.getSupportedStyles() // [dependent/annals-of-occupational-and-environmental-medicine, dependent/photoacoustics, dependent/statistical-science, twentieth-century-music, dependent/aims-medical-science, dependent/cell-systems, dependent/nursingplus-open, dependent/computer-science-review,...]
P.S: To running on AndroidStudio I had to add these lines in build.gradle
android{
...
packagingOptions {
exclude 'META-INF/truffle/language'
}
}
When verifying the signature, the background server displays {"rtnCode":-1,"errMsg":"check playerSSign fail"}
The data provided by the client is
if(huaweiid != null){
PlayersClient player = Games.getPlayersClient(this, huaweiid);
player.getCurrentPlayer().addOnSuccessListener(new OnSuccessListener<Player>() {
#Override
public void onSuccess(Player player) {
String ts = player.getSignTs();
String playerId = player.getPlayerId();
int playerLevel = player.getLevel();
String playerSign = player.getPlayerSign();
//String displayName = player.getDisplayName();
//Uri hiResImageUri = player.getHiResImageUri();
//Uri iconImageUri = player.getIconImageUri();
JSONObject jo = new JSONObject();
try {
jo.put("signTs", ts);
jo.put("playerId", playerId);
jo.put("playerLevel", playerLevel);
jo.put("playerSign", playerSign);
EditText ed = findViewById(R.id.editText);
ed.setText(jo.toString());
Log.i("huawei user info", jo.toString());
} catch (JSONException e) {
e.printStackTrace();
Log.i("huawei user info", Objects.requireNonNull(e.getMessage()));
}
}
});
}
Use the preceding four data items and the following description document:
https://developer.huawei.com/consumer/cn/doc/HMSCore-References-V5/verify-login-signature-0000001050123503-V5
An error always occurs during the verification in the background.
{"rtnCode":-1,"errMsg":"check playerSSign fail"}
appId/cpid is obtained from agconnect-services.json and agconnect-services.json is downloaded from the background.
what’s the reason?
The following table describes the typical setting errors of the input parameters. Please verify the parameter settings.
https://developer.huawei.com/consumer/cn/doc/development/AppGallery-connect-Guides/faq-check-login-0000001050746133-V5
I am trying to make an app that would send a MMS without using the native Android messaging app. I followed the example here. My log statements seem to be correctly printing, but I can't figure out why the MMS is not being sent.
Also on a different note, I am a bit confused about where in the example the attachment (like an image) is being selected to send as MMS. I tried to import the demo into Android Studio but I ran into issues.
My function for sending MMS is below:
public void sendMMS() {
Log.d(TAG, "sendMMS()");
Random random = new Random();
final String fileName = "send." + String.valueOf(Math.abs(random.nextLong())) + ".dat";
final File mSendFile = new File(mContext.getCacheDir(), fileName);
// Making RPC call in non-UI thread
AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
#Override
public void run() {
final byte[] pdu = buildPdu();
Uri writerUri = (new Uri.Builder())
.authority("com.example.appname")
.path(fileName)
.scheme(ContentResolver.SCHEME_CONTENT)
.build();
Log.d(TAG, "sendMMS(): Uri: " + writerUri.toString());
FileOutputStream writer = null;
Uri contentUri = null;
try {
writer = new FileOutputStream(mSendFile);
writer.write(pdu);
contentUri = writerUri;
Log.d(TAG, "sendMMS(): just wrote file");
} catch (final IOException e) {
Log.d(TAG, "sendMMS(): FAILED: couldn't write file");
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
}
}
}
if (contentUri != null) {
SmsManager.getDefault().sendMultimediaMessage(mContext, contentUri, null, null, null);
Log.d(TAG, "sendMMS(): just sent");
} else {
Log.d(TAG, "sendMMS(): FAILED: couldn't write file so didn't send");
}
}
});
}
Helper functions
private byte[] buildPdu() {
final SendReq req = new SendReq();
// from
final String lineNumber = getSimNumber();
if (!TextUtils.isEmpty(lineNumber)) {
req.setFrom(new EncodedStringValue(lineNumber));
}
// to
String[] destsArray = mDestList.toArray(new String[mDestList.size()]);
EncodedStringValue[] encodedNumbers = EncodedStringValue.encodeStrings(destsArray);
if (encodedNumbers != null) {
req.setTo(encodedNumbers);
}
// date
req.setDate(System.currentTimeMillis() / 1000);
// body
PduBody body = new PduBody();
// message text
final int size = addMessagePart(body, true/* add text smil */);
req.setBody(body);
// message size
req.setMessageSize(size);
// message class
req.setMessageClass(PduHeaders.MESSAGE_CLASS_PERSONAL_STR.getBytes());
// expiry
req.setExpiry(DEFAULT_EXPIRY_TIME);
try {
// priority
req.setPriority(DEFAULT_PRIORITY);
// delivery report
req.setDeliveryReport(PduHeaders.VALUE_NO);
// read report
req.setReadReport(PduHeaders.VALUE_NO);
} catch (InvalidHeaderValueException e) {}
return new PduComposer(mContext, req).make();
}
private String getSimNumber() {
TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
return telephonyManager.getLine1Number();
}
private int addMessagePart(PduBody pb, boolean addTextSmil) {
PduPart part = new PduPart();
part.setCharset(CharacterSets.UTF_8);
part.setContentType(ContentType.TEXT_PLAIN.getBytes());
part.setContentLocation(TEXT_PART_FILENAME.getBytes());
int index = TEXT_PART_FILENAME.lastIndexOf(".");
String contentId = (index == -1) ? TEXT_PART_FILENAME : TEXT_PART_FILENAME.substring(0, index);
part.setContentId(contentId.getBytes());
part.setData(mMessage.getBytes());
pb.addPart(part);
if (addTextSmil) {
String smil = String.format(sSmilText, TEXT_PART_FILENAME);
addSmilPart(pb, smil);
}
return part.getData().length;
}
private void addSmilPart(PduBody pb, String smil) {
PduPart smilPart = new PduPart();
smilPart.setContentId("smil".getBytes());
smilPart.setContentType(ContentType.APP_SMIL.getBytes());
smilPart.setContentLocation("smil.xml".getBytes());
smilPart.setData(smil.getBytes());
pb.addPart(0, smilPart);
}
Relevant parts of my manifest
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Relevant instance variables
private final long DEFAULT_EXPIRY_TIME = 7 * 24 * 60 * 60;
private final String TEXT_PART_FILENAME = "text_0.txt";
private final int DEFAULT_PRIORITY = PduHeaders.PRIORITY_NORMAL;
private String mMessage;
private ArrayList<String> mDestList;
private Context mContext;
private static final String sSmilText =
"<smil>" +
"<head>" +
"<layout>" +
"<root-layout/>" +
"<region height=\"100%%\" id=\"Text\" left=\"0%%\" top=\"0%%\" width=\"100%%\"/>" +
"</layout>" +
"</head>" +
"<body>" +
"<par dur=\"8000ms\">" +
"<text src=\"%s\" region=\"Text\"/>" +
"</par>" +
"</body>" +
"</smil>";
I already do input checks, so by the time sendMMS() is called, my message and destList are not null.
The flow should be as such:
Create the Mms send-request - new SendReq() and config its date, body, to, etc.
Create the Mms body - new PduBody().
Create Parts via new PduPart() for each attachment, and add to the body: body.addPart(pdu)
Add the body to the request - req.setBody(body)
Convert the send-request to a byte[] ready to be sent by calling new PduComposer(context, mySendReq).make() - note that you'll need to copy lots of code from Android's source code to get the PduComposer class.
Now's the interesting part - you save the byte[] to a local file accessible to your app only, and add ContentProvider class that allows other apps to request access to your file, this is MmsFileProvider class in the sample app, don't forget to declare your provider in your manifest file.
Now, when you call the SmsManager.sendMultimediaMessage api, your file provider will wake up to serve the file containing the pdu bytes to the system SmsManager that will read it and send it on the wire.
Having that said, this API is only working for me on some devices (e.g. Nexuses), but not on some others (e.g. HTC One).
See my SO question here:
SmsManager MMS APIs on HTC/LG
I'm having problems when I want to generate a long shareable url to a file with Dropbox SDK for Android. I mean, I have not found a way to create that url.
For example, I have a file called profile_image.jpg in app folder. I upload the file with this code (like Dropbox example):
public String subirImagenDropbox(File file) {
AndroidAuthSession sesion = buildSession(); //Like the Dropbox Example
DropboxAPI<AndroidAuthSession> mApi = new DropboxAPI<AndroidAuthSession>(sesion);
checkAppKey();
try {
FileInputStream fis = new FileInputStream(file);
String name = file.getName();
mRequest = mApi.putFileOverwriteRequest("/empleados/img_perfil/" + name,
fis,
file.length(),
new ProgressListener() {
#Override
public long progressInterval() {
return 100;
}
#Override
public void onProgress(long bytes, long total) {
System.err.println(bytes + " bytes de " + total);
}
});
if (mRequest != null) {
DropboxAPI.Entry upload = mRequest.upload(); //Here upload to Dropbox
DropboxAPI.DropboxLink share = mApi.share(upload.path); //Generate short shareable URL. Expire in 31 days
System.err.println("URL: " + share.url); //Print in LogCat for debug purpose
}
}
//... A lot catchs ...
return ""; //Return the long shareable URL
}
This code upload the file perfectly, but the shareable url is like this:
http://db.tt/abcd123
and I want (I added ?dl=1):
https://www.dropbox.com/s/abcdefghi1234567/profile_image.jpg?dl=1
(I added ?dl=1).
I did it with Java SDK (dbxClient.createShareableUrl(metadata.path)) but in Android is different. I hope someone can help me with this minor inconvenience.
Thanks!
I'm trying to upload multiple images to a PHP server along with a few other parameters (strings), using the POST method. I'm using Multipart method. I added 4 libraries prescribed in various solutions (apachemime, httpclient, httpmime, httpcore), but my SDK doesn't recognise MultipartEntity, displaying the error: 'cannot be resolved to a type'. I've also tried MultipartEntityBuilder, but even that's showing the same error. I basically want to upload a Bitmap Arraylist to the server & show a progress bar simultaneously.
You should post some code with the issue so we can take a look and help you.
But if you want to try something a little bit simple you can use this library, AsyncHttpClient: http://loopj.com/android-async-http/
Using this library you could post multiple files like this:
private static AsyncHttpClient clientHttp = new AsyncHttpClient();
...
RequestParams params = new RequestParams();
final String TAG_FILE = "archivo1";
final String TAG_FILE_1 = "archivo2";
final String TAG_FILE_2 = "archivo3";
final String PATH_FILE_1 = ApplicationContext.getInstance().getFilesDir().getPath() + "/" + "file1.jpg";
final String PATH_FILE_2 = ApplicationContext.getInstance().getFilesDir().getPath() + "/" + "file2.jpg";
final String PATH_FILE_3 = ApplicationContext.getInstance().getFilesDir().getPath() + "/" + "file3.jpg";
try {
params.put(TAG_FILE, PATH_FILE_1);
params.put(TAG_FILE_1, PATH_FILE_2);
params.put(TAG_FILE_2, PATH_FILE_3);
params.put(TAG_PARAM, "SOME TEXT");
}
catch(FileNotFoundException e) {
//Manage your exception
}
final int DEFAULT_TIMEOUT = 30 * 1000;
clientHttp.setTimeout(DEFAULT_TIMEOUT);
clientHttp.post("http://somereceiver.php", params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONObject response) {
//Do your code on success
}
#Override
public void onStart() {
// Show your progress bar
}
#Override
public void onFinish() {
// Hide your progress bar
super.onFinish();
if(PATH_FILE_1 != null) {
File tem = new File(PATH_FILE_1);
if(tem.exists()) tem.delete();
}
if(PATH_FILE_2 != null) {
File tem = new File(PATH_FILE_2);
if(tem.exists()) tem.delete();
}
if(PATH_FILE_3 != null) {
File tem = new File(PATH_FILE_3);
if(tem.exists()) tem.delete();
}
}
});
You could also use the generic response type if you dont need json, so you get a string.
Hope this helps.