List of usage examples for java.lang OutOfMemoryError getLocalizedMessage
public String getLocalizedMessage()
From source file:org.matrix.androidsdk.db.MXMediaDownloadWorkerTask.java
/** * Search a cached bitmap from an url.//from w ww . j a va 2 s. c om * rotationAngle is set to Integer.MAX_VALUE when undefined : the EXIF metadata must be checked. * * @param baseFile the base file * @param url the media url * @param rotation the bitmap rotation * @param mimeType the mime type * @return the cached bitmap */ public static Bitmap bitmapForURL(Context context, File baseFile, String url, int rotation, String mimeType) { Bitmap bitmap = null; // sanity check if (null != url) { if (null == mBitmapByUrlCache) { int lruSize = Math.min(20 * 1024 * 1024, (int) Runtime.getRuntime().maxMemory() / 8); Log.d(LOG_TAG, "bitmapForURL lruSize : " + lruSize); mBitmapByUrlCache = new LruCache<String, Bitmap>(lruSize) { @Override protected int sizeOf(String key, Bitmap bitmap) { return bitmap.getRowBytes() * bitmap.getHeight(); // size in bytes } }; } // the image is downloading in background if (null != getMediaDownloadWorkerTask(url)) { return null; } // the url is invalid if (isMediaUrlUnreachable(url)) { return null; } synchronized (mSyncObject) { bitmap = mBitmapByUrlCache.get(url); } // check if the image has not been saved in file system if ((null == bitmap) && (null != baseFile)) { String filename = null; // the url is a file one if (url.startsWith("file:")) { // try to parse it try { Uri uri = Uri.parse(url); filename = uri.getPath(); } catch (Exception e) { Log.e(LOG_TAG, "bitmapForURL #1 : " + e.getLocalizedMessage()); } // cannot extract the filename -> sorry if (null == filename) { return null; } } // not a valid file name if (null == filename) { filename = buildFileName(url, mimeType); } try { File file = filename.startsWith(File.separator) ? new File(filename) : new File(baseFile, filename); if (!file.exists()) { Log.d(LOG_TAG, "bitmapForURL() : " + filename + " does not exist"); return null; } InputStream fis = new FileInputStream(file); // read the metadata if (Integer.MAX_VALUE == rotation) { rotation = ImageUtils.getRotationAngleForBitmap(context, Uri.fromFile(file)); } if (null != fis) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; try { bitmap = BitmapFactory.decodeStream(fis, null, options); } catch (OutOfMemoryError error) { System.gc(); Log.e(LOG_TAG, "bitmapForURL() : Out of memory 1 " + error); } // try again if (null == bitmap) { try { bitmap = BitmapFactory.decodeStream(fis, null, options); } catch (OutOfMemoryError error) { Log.e(LOG_TAG, "bitmapForURL() Out of memory 2" + error); } } if (null != bitmap) { synchronized (mSyncObject) { if (0 != rotation) { try { android.graphics.Matrix bitmapMatrix = new android.graphics.Matrix(); bitmapMatrix.postRotate(rotation); Bitmap transformedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), bitmapMatrix, false); bitmap.recycle(); bitmap = transformedBitmap; } catch (OutOfMemoryError ex) { Log.e(LOG_TAG, "bitmapForURL rotation error : " + ex.getLocalizedMessage()); } } // cache only small images // caching large images does not make sense // it would replace small ones. // let assume that the application must be faster when showing the chat history. if ((bitmap.getWidth() < 1000) && (bitmap.getHeight() < 1000)) { mBitmapByUrlCache.put(url, bitmap); } } } fis.close(); } } catch (FileNotFoundException e) { Log.d(LOG_TAG, "bitmapForURL() : " + filename + " does not exist"); } catch (Exception e) { Log.e(LOG_TAG, "bitmapForURL() " + e); } } } return bitmap; }
From source file:jahirfiquitiva.iconshowcase.tasks.ApplyWallpaper.java
@Override protected Boolean doInBackground(Void... params) { Boolean worked = false;//from w ww .j a v a2s. c o m if ((!wasCancelled) && (activity != null)) { WallpaperManager wm = WallpaperManager.getInstance(activity); try { try { wm.setBitmap(scaleToActualAspectRatio(resource)); } catch (OutOfMemoryError ex) { if (ShowcaseActivity.DEBUGGING) Utils.showLog(activity, "OutOfMemoryError: " + ex.getLocalizedMessage()); showRetrySnackbar(); } worked = true; } catch (IOException e2) { worked = false; } } else { worked = false; } return worked; }
From source file:de.blinkt.openvpn.core.ConfigParser.java
public void parseConfig(Reader reader) throws IOException, ConfigParseError { HashMap<String, String> optionAliases = new HashMap<>(); optionAliases.put("server-poll-timeout", "timeout-connect"); BufferedReader br = new BufferedReader(reader); int lineno = 0; try {// w ww . jav a 2 s . c o m while (true) { String line = br.readLine(); lineno++; if (line == null) break; if (lineno == 1) { if ((line.startsWith("PK\003\004") || (line.startsWith("PK\007\008")))) { throw new ConfigParseError( "Input looks like a ZIP Archive. Import is only possible for OpenVPN config files (.ovpn/.conf)"); } if (line.startsWith("\uFEFF")) { line = line.substring(1); } } // Check for OpenVPN Access Server Meta information if (line.startsWith("# OVPN_ACCESS_SERVER_")) { Vector<String> metaarg = parsemeta(line); meta.put(metaarg.get(0), metaarg); continue; } Vector<String> args = parseline(line); if (args.size() == 0) continue; if (args.get(0).startsWith("--")) args.set(0, args.get(0).substring(2)); checkinlinefile(args, br); String optionname = args.get(0); if (optionAliases.get(optionname) != null) optionname = optionAliases.get(optionname); if (!options.containsKey(optionname)) { options.put(optionname, new Vector<Vector<String>>()); } options.get(optionname).add(args); } } catch (OutOfMemoryError memoryError) { throw new ConfigParseError("File too large to parse: " + memoryError.getLocalizedMessage()); } }
From source file:nf.frex.android.FrexActivity.java
private void setWallpaper(WallpaperManager wallpaperManager, Image image) { try {//from ww w . j a v a 2 s .c om wallpaperManager.setBitmap(image.createBitmap()); alert(R.string.wallpaper_set_msg); } catch (OutOfMemoryError e) { alert(getString(R.string.out_of_memory)); } catch (IOException e) { alert(e.getLocalizedMessage()); } }
From source file:com.zld.ui.ZldNewActivity.java
@Override public void onDataReceive(int handle, PlateResult plateResult, int uNumPlates, int eResultType, byte[] pImgFull, int nFullSize, byte[] pImgPlateClip, int nClipSize) { try {/*from w w w .j a va 2 s . co m*/ DeviceSet ds = this.getDeviceSetFromHandle(handle); if (ds == null) { Toast.makeText(ZldNewActivity.this, "?:", Toast.LENGTH_SHORT) .show(); } DeviceInfo di = ds.getDeviceInfo(); String dateText = ""; dateText += plateResult.struBDTime.bdt_year; dateText += "/"; dateText += plateResult.struBDTime.bdt_mon; dateText += "/"; dateText += plateResult.struBDTime.bdt_mday; dateText += " "; dateText += plateResult.struBDTime.bdt_hour; dateText += ":"; dateText += plateResult.struBDTime.bdt_min; dateText += ":"; dateText += plateResult.struBDTime.bdt_sec; String plateText = new String(plateResult.license, "GBK"); if (!m_gb.getplateCallbackInfoTable().addCallbackInfo(di.DeviceName, plateText, dateText, pImgFull, pImgPlateClip)) { Toast.makeText(ZldNewActivity.this, "?", Toast.LENGTH_SHORT).show(); } Log.i("visizion", "decodeByteArray begin"); BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 4;//??? options.inInputShareable = true; Bitmap bmp; try { bmp = BitmapFactory.decodeByteArray(pImgFull, 0, pImgFull.length, options); if (bmp != null) { Message msg = new Message(); msg.what = PlateImage; msg.arg1 = ds.getDeviceInfo().id; msg.obj = bmp; Bundle data = new Bundle(); data.putString("plate", plateText); msg.setData(data); handler.sendMessage(msg); } } catch (OutOfMemoryError e) { Log.e("Map", "Tile Loader (241) Out Of Memory Error " + e.getLocalizedMessage()); System.gc(); } catch (Exception e) { e.printStackTrace(); } finally { Log.i("visizion", "decodeByteArray end"); } } catch (UnsupportedEncodingException e) { Toast.makeText(ZldNewActivity.this, "???", Toast.LENGTH_SHORT).show(); } }
From source file:com.hichinaschool.flashcards.async.Connection.java
private Payload doInBackgroundSync(Payload data) { // for for doInBackgroundLoadDeckCounts if any DeckTask.waitToFinish();/*w w w . j av a 2s .c o m*/ String hkey = (String) data.data[0]; boolean media = (Boolean) data.data[1]; String conflictResolution = (String) data.data[2]; int mediaUsn = (Integer) data.data[3]; boolean colCorruptFullSync = false; Collection col = AnkiDroidApp.getCol(); if (!AnkiDroidApp.colIsOpen()) { if (conflictResolution != null && conflictResolution.equals("download")) { colCorruptFullSync = true; } else { data.success = false; data.result = new Object[] { "genericError" }; return data; } } String path = AnkiDroidApp.getCollectionPath(); BasicHttpSyncer server = new RemoteServer(this, hkey); Syncer client = new Syncer(col, server); // run sync and check state boolean noChanges = false; if (conflictResolution == null) { // Log.i(AnkiDroidApp.TAG, "Sync - starting sync"); publishProgress(R.string.sync_prepare_syncing); Object[] ret = client.sync(this); data.message = client.getSyncMsg(); mediaUsn = client.getmMediaUsn(); if (ret == null) { data.success = false; data.result = new Object[] { "genericError" }; return data; } String retCode = (String) ret[0]; if (!retCode.equals("noChanges") && !retCode.equals("success")) { data.success = false; data.result = ret; // note mediaUSN for later data.data = new Object[] { mediaUsn }; return data; } // save and note success state if (retCode.equals("noChanges")) { // publishProgress(R.string.sync_no_changes_message); noChanges = true; } else { // publishProgress(R.string.sync_database_success); } } else { try { server = new FullSyncer(col, hkey, this); if (conflictResolution.equals("upload")) { // Log.i(AnkiDroidApp.TAG, "Sync - fullsync - upload collection"); publishProgress(R.string.sync_preparing_full_sync_message); Object[] ret = server.upload(); if (ret == null) { data.success = false; data.result = new Object[] { "genericError" }; AnkiDroidApp.openCollection(path); return data; } if (!((String) ret[0]).equals(BasicHttpSyncer.ANKIWEB_STATUS_OK)) { data.success = false; data.result = ret; AnkiDroidApp.openCollection(path); return data; } } else if (conflictResolution.equals("download")) { // Log.i(AnkiDroidApp.TAG, "Sync - fullsync - download collection"); publishProgress(R.string.sync_downloading_message); Object[] ret = server.download(); if (ret == null) { data.success = false; data.result = new Object[] { "genericError" }; AnkiDroidApp.openCollection(path); return data; } if (!((String) ret[0]).equals("success")) { data.success = false; data.result = ret; if (!colCorruptFullSync) { AnkiDroidApp.openCollection(path); } return data; } } col = AnkiDroidApp.openCollection(path); } catch (OutOfMemoryError e) { AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundSync-fullSync"); data.success = false; data.result = new Object[] { "OutOfMemoryError" }; data.data = new Object[] { mediaUsn }; return data; } catch (RuntimeException e) { AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundSync-fullSync"); data.success = false; data.result = new Object[] { "IOException" }; data.data = new Object[] { mediaUsn }; return data; } } // clear undo to avoid non syncing orphans (because undo resets usn too if (!noChanges) { col.clearUndo(); } // then move on to media sync boolean noMediaChanges = false; String mediaError = null; if (media) { server = new RemoteMediaServer(hkey, this); MediaSyncer mediaClient = new MediaSyncer(col, (RemoteMediaServer) server); String ret; try { ret = mediaClient.sync(mediaUsn, this); if (ret == null) { mediaError = AnkiDroidApp.getAppResources().getString(R.string.sync_media_error); } else { if (ret.equals("noChanges")) { publishProgress(R.string.sync_media_no_changes); noMediaChanges = true; } if (ret.equals("sanityFailed")) { mediaError = AnkiDroidApp.getAppResources().getString(R.string.sync_media_sanity_failed); } else { publishProgress(R.string.sync_media_success); } } } catch (RuntimeException e) { AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundSync-mediaSync"); mediaError = e.getLocalizedMessage(); } } if (noChanges && noMediaChanges) { data.success = false; data.result = new Object[] { "noChanges" }; return data; } else { data.success = true; TreeSet<Object[]> decks = col.getSched().deckDueTree(); int[] counts = new int[] { 0, 0, 0 }; for (Object[] deck : decks) { if (((String[]) deck[0]).length == 1) { counts[0] += (Integer) deck[2]; counts[1] += (Integer) deck[3]; counts[2] += (Integer) deck[4]; } } Object[] dc = col.getSched().deckCounts(); data.result = dc[0]; data.data = new Object[] { conflictResolution, col, dc[1], dc[2], mediaError }; return data; } }
From source file:com.ichi2.async.Connection.java
private Payload doInBackgroundSync(Payload data) { // for for doInBackgroundLoadDeckCounts if any sIsCancellable = true;/* w w w. ja v a 2 s .c om*/ Timber.d("doInBackgroundSync()"); // Block execution until any previous background task finishes, or timeout after 5s boolean ok = DeckTask.waitToFinish(5); String hkey = (String) data.data[0]; boolean media = (Boolean) data.data[1]; String conflictResolution = (String) data.data[2]; Collection col = CollectionHelper.getInstance().getCol(AnkiDroidApp.getInstance()); boolean colCorruptFullSync = false; if (!CollectionHelper.getInstance().colIsOpen() || !ok) { if (conflictResolution != null && conflictResolution.equals("download")) { colCorruptFullSync = true; } else { data.success = false; data.result = new Object[] { "genericError" }; return data; } } try { CollectionHelper.getInstance().lockCollection(); HttpSyncer server = new RemoteServer(this, hkey); Syncer client = new Syncer(col, server); // run sync and check state boolean noChanges = false; if (conflictResolution == null) { Timber.i("Sync - starting sync"); publishProgress(R.string.sync_prepare_syncing); Object[] ret = client.sync(this); data.message = client.getSyncMsg(); if (ret == null) { data.success = false; data.result = new Object[] { "genericError" }; return data; } String retCode = (String) ret[0]; if (!retCode.equals("noChanges") && !retCode.equals("success")) { data.success = false; data.result = ret; // Check if there was a sanity check error if (retCode.equals("sanityCheckError")) { // Force full sync next time col.modSchemaNoCheck(); col.save(); } return data; } // save and note success state if (retCode.equals("noChanges")) { // publishProgress(R.string.sync_no_changes_message); noChanges = true; } else { // publishProgress(R.string.sync_database_acknowledge); } } else { try { // Disable sync cancellation for full-sync sIsCancellable = false; server = new FullSyncer(col, hkey, this); if (conflictResolution.equals("upload")) { Timber.i("Sync - fullsync - upload collection"); publishProgress(R.string.sync_preparing_full_sync_message); Object[] ret = server.upload(); if (ret == null) { data.success = false; data.result = new Object[] { "genericError" }; CollectionHelper.getInstance().reopenCollection(); // TODO: is this needed? return data; } if (!ret[0].equals(HttpSyncer.ANKIWEB_STATUS_OK)) { data.success = false; data.result = ret; CollectionHelper.getInstance().reopenCollection(); // TODO: is this needed? return data; } } else if (conflictResolution.equals("download")) { Timber.i("Sync - fullsync - download collection"); publishProgress(R.string.sync_downloading_message); Object[] ret = server.download(); if (ret == null) { data.success = false; data.result = new Object[] { "genericError" }; CollectionHelper.getInstance().reopenCollection(); // TODO: is this needed? return data; } if (!ret[0].equals("success")) { data.success = false; data.result = ret; if (!colCorruptFullSync) { CollectionHelper.getInstance().reopenCollection(); // TODO: is this needed? } return data; } } col = CollectionHelper.getInstance().reopenCollection(); // TODO: is this needed? } catch (OutOfMemoryError e) { AnkiDroidApp.sendExceptionReport(e, "doInBackgroundSync-fullSync"); data.success = false; data.result = new Object[] { "OutOfMemoryError" }; return data; } catch (RuntimeException e) { if (timeoutOccured(e)) { data.result = new Object[] { "connectionError" }; } else if (e.getMessage().equals("UserAbortedSync")) { data.result = new Object[] { "UserAbortedSync" }; } else { AnkiDroidApp.sendExceptionReport(e, "doInBackgroundSync-fullSync"); data.result = new Object[] { "IOException" }; } data.success = false; return data; } } // clear undo to avoid non syncing orphans (because undo resets usn too if (!noChanges) { col.clearUndo(); } // then move on to media sync sIsCancellable = true; boolean noMediaChanges = false; String mediaError = null; if (media) { server = new RemoteMediaServer(col, hkey, this); MediaSyncer mediaClient = new MediaSyncer(col, (RemoteMediaServer) server, this); String ret; try { ret = mediaClient.sync(); if (ret == null) { mediaError = AnkiDroidApp.getAppResources().getString(R.string.sync_media_error); } else { if (ret.equals("noChanges")) { publishProgress(R.string.sync_media_no_changes); noMediaChanges = true; } if (ret.equals("sanityFailed")) { mediaError = AnkiDroidApp.getAppResources() .getString(R.string.sync_media_sanity_failed); } else { publishProgress(R.string.sync_media_success); } } } catch (RuntimeException e) { if (timeoutOccured(e)) { data.result = new Object[] { "connectionError" }; } else if (e.getMessage().equals("UserAbortedSync")) { data.result = new Object[] { "UserAbortedSync" }; } else { AnkiDroidApp.sendExceptionReport(e, "doInBackgroundSync-mediaSync"); } mediaError = e.getLocalizedMessage(); } } if (noChanges && (!media || noMediaChanges)) { data.success = false; data.result = new Object[] { "noChanges" }; return data; } else { data.success = true; data.data = new Object[] { conflictResolution, col, mediaError }; return data; } } catch (MediaSyncException e) { Timber.e("Media sync rejected by server"); data.success = false; data.result = new Object[] { "mediaSyncServerError" }; AnkiDroidApp.sendExceptionReport(e, "doInBackgroundSync"); return data; } catch (UnknownHttpResponseException e) { Timber.e("doInBackgroundSync -- unknown response code error"); e.printStackTrace(); data.success = false; Integer code = e.getResponseCode(); String msg = e.getLocalizedMessage(); data.result = new Object[] { "error", code, msg }; return data; } catch (Exception e) { // Global error catcher. // Try to give a human readable error, otherwise print the raw error message Timber.e("doInBackgroundSync error"); e.printStackTrace(); data.success = false; if (timeoutOccured(e)) { data.result = new Object[] { "connectionError" }; } else if (e.getMessage().equals("UserAbortedSync")) { data.result = new Object[] { "UserAbortedSync" }; } else { AnkiDroidApp.sendExceptionReport(e, "doInBackgroundSync"); data.result = new Object[] { e.getLocalizedMessage() }; } return data; } finally { // Close collection to roll back any sync failures and Timber.d("doInBackgroundSync -- closing collection on outer finally statement"); col.close(false); CollectionHelper.getInstance().unlockCollection(); Timber.d("doInBackgroundSync -- reopening collection on outer finally statement"); CollectionHelper.getInstance().reopenCollection(); } }
From source file:website.openeng.async.Connection.java
private Payload doInBackgroundSync(Payload data) { // for for doInBackgroundLoadDeckCounts if any Timber.d("doInBackgroundSync()"); // Block execution until any previous background task finishes, or timeout after 5s boolean ok = DeckTask.waitToFinish(5); String hkey = (String) data.data[0]; boolean media = (Boolean) data.data[1]; String conflictResolution = (String) data.data[2]; Collection col = data.col;//w ww . j a v a 2s . c o m boolean colCorruptFullSync = false; if (!CollectionHelper.getInstance().colIsOpen() || !ok) { if (conflictResolution != null && conflictResolution.equals("download")) { colCorruptFullSync = true; } else { data.success = false; data.result = new Object[] { "genericError" }; return data; } } try { CollectionHelper.getInstance().lockCollection(); HttpSyncer server = new RemoteServer(this, hkey); Syncer client = new Syncer(col, server); // run sync and check state boolean noChanges = false; if (conflictResolution == null) { Timber.i("Sync - starting sync"); publishProgress(R.string.sync_prepare_syncing); Object[] ret = client.sync(this); data.message = client.getSyncMsg(); if (ret == null) { data.success = false; data.result = new Object[] { "genericError" }; return data; } String retCode = (String) ret[0]; if (!retCode.equals("noChanges") && !retCode.equals("success")) { data.success = false; data.result = ret; // Check if there was a sanity check error if (retCode.equals("sanityCheckError")) { // Force full sync next time col.modSchemaNoCheck(); col.save(); } return data; } // save and note success state if (retCode.equals("noChanges")) { // publishProgress(R.string.sync_no_changes_message); noChanges = true; } else { // publishProgress(R.string.sync_database_acknowledge); } } else { try { server = new FullSyncer(col, hkey, this); if (conflictResolution.equals("upload")) { Timber.i("Sync - fullsync - upload collection"); publishProgress(R.string.sync_preparing_full_sync_message); Object[] ret = server.upload(); if (ret == null) { data.success = false; data.result = new Object[] { "genericError" }; CollectionHelper.getInstance().reopenCollection(); // TODO: is this needed? return data; } if (!ret[0].equals(HttpSyncer.ANKIWEB_STATUS_OK)) { data.success = false; data.result = ret; CollectionHelper.getInstance().reopenCollection(); // TODO: is this needed? return data; } } else if (conflictResolution.equals("download")) { Timber.i("Sync - fullsync - download collection"); publishProgress(R.string.sync_downloading_message); Object[] ret = server.download(); if (ret == null) { data.success = false; data.result = new Object[] { "genericError" }; CollectionHelper.getInstance().reopenCollection(); // TODO: is this needed? return data; } if (!ret[0].equals("success")) { data.success = false; data.result = ret; if (!colCorruptFullSync) { CollectionHelper.getInstance().reopenCollection(); // TODO: is this needed? } return data; } } col = CollectionHelper.getInstance().reopenCollection(); // TODO: is this needed? } catch (OutOfMemoryError e) { KanjiDroidApp.sendExceptionReport(e, "doInBackgroundSync-fullSync"); data.success = false; data.result = new Object[] { "OutOfMemoryError" }; return data; } catch (RuntimeException e) { if (timeoutOccured(e)) { data.result = new Object[] { "connectionError" }; } else { KanjiDroidApp.sendExceptionReport(e, "doInBackgroundSync-fullSync"); data.result = new Object[] { "IOException" }; } data.success = false; return data; } } // clear undo to avoid non syncing orphans (because undo resets usn too if (!noChanges) { col.clearUndo(); } // then move on to media sync boolean noMediaChanges = false; String mediaError = null; if (media) { server = new RemoteMediaServer(col, hkey, this); MediaSyncer mediaClient = new MediaSyncer(col, (RemoteMediaServer) server, this); String ret; try { ret = mediaClient.sync(); if (ret == null) { mediaError = KanjiDroidApp.getAppResources().getString(R.string.sync_media_error); } else { if (ret.equals("noChanges")) { publishProgress(R.string.sync_media_no_changes); noMediaChanges = true; } if (ret.equals("sanityFailed")) { mediaError = KanjiDroidApp.getAppResources() .getString(R.string.sync_media_sanity_failed); } else { publishProgress(R.string.sync_media_success); } } } catch (UnsupportedSyncException e) { mediaError = KanjiDroidApp.getAppResources().getString(R.string.sync_media_unsupported); KanjiDroidApp.getSharedPrefs(KanjiDroidApp.getInstance().getApplicationContext()).edit() .putBoolean("syncFetchesMedia", false).commit(); KanjiDroidApp.sendExceptionReport(e, "doInBackgroundSync-mediaSync"); } catch (RuntimeException e) { if (timeoutOccured(e)) { data.result = new Object[] { "connectionError" }; } else { KanjiDroidApp.sendExceptionReport(e, "doInBackgroundSync-mediaSync"); } mediaError = e.getLocalizedMessage(); } } if (noChanges && noMediaChanges) { data.success = false; data.result = new Object[] { "noChanges" }; return data; } else { data.success = true; data.data = new Object[] { conflictResolution, col, mediaError }; return data; } } catch (UnknownHttpResponseException e) { Timber.e("doInBackgroundSync -- unknown response code error"); e.printStackTrace(); data.success = false; Integer code = e.getResponseCode(); String msg = e.getLocalizedMessage(); data.result = new Object[] { "error", code, msg }; return data; } catch (Exception e) { // Global error catcher. // Try to give a human readable error, otherwise print the raw error message Timber.e("doInBackgroundSync error"); e.printStackTrace(); data.success = false; if (timeoutOccured(e)) { data.result = new Object[] { "connectionError" }; } else { KanjiDroidApp.sendExceptionReport(e, "doInBackgroundSync"); data.result = new Object[] { e.getLocalizedMessage() }; } return data; } finally { // Close collection to roll back any sync failures and Timber.d("doInBackgroundSync -- closing collection on outer finally statement"); col.close(false); CollectionHelper.getInstance().unlockCollection(); Timber.d("doInBackgroundSync -- reopening collection on outer finally statement"); CollectionHelper.getInstance().reopenCollection(); } }
From source file:im.vector.util.BugReporter.java
/** * Send a bug report.//w w w.ja v a2 s . co m * * @param context the application context * @param withDevicesLogs true to include the device logs * @param withCrashLogs true to include the crash logs */ private static void sendBugReport(final Context context, final boolean withDevicesLogs, final boolean withCrashLogs, final String bugDescription, final IMXBugReportListener listener) { new AsyncTask<Void, Integer, String>() { @Override protected String doInBackground(Void... voids) { File bugReportFile = new File(context.getApplicationContext().getFilesDir(), "bug_report"); if (bugReportFile.exists()) { bugReportFile.delete(); } String serverError = null; FileWriter fileWriter = null; try { fileWriter = new FileWriter(bugReportFile); JsonWriter jsonWriter = new JsonWriter(fileWriter); jsonWriter.beginObject(); // android bug report jsonWriter.name("user_agent").value("Android"); // logs list jsonWriter.name("logs"); jsonWriter.beginArray(); // the logs are optional if (withDevicesLogs) { List<File> files = org.matrix.androidsdk.util.Log.addLogFiles(new ArrayList<File>()); for (File f : files) { if (!mIsCancelled) { jsonWriter.beginObject(); jsonWriter.name("lines").value(convertStreamToString(f)); jsonWriter.endObject(); jsonWriter.flush(); } } } if (!mIsCancelled && (withCrashLogs || withDevicesLogs)) { jsonWriter.beginObject(); jsonWriter.name("lines").value(getLogCatError()); jsonWriter.endObject(); jsonWriter.flush(); } jsonWriter.endArray(); jsonWriter.name("text").value(bugDescription); String version = ""; if (null != Matrix.getInstance(context).getDefaultSession()) { version += "User : " + Matrix.getInstance(context).getDefaultSession().getMyUserId() + "\n"; } version += "Phone : " + Build.MODEL.trim() + " (" + Build.VERSION.INCREMENTAL + " " + Build.VERSION.RELEASE + " " + Build.VERSION.CODENAME + ")\n"; version += "Vector version: " + Matrix.getInstance(context).getVersion(true) + "\n"; version += "SDK version: " + Matrix.getInstance(context).getDefaultSession().getVersion(true) + "\n"; version += "Olm version: " + Matrix.getInstance(context).getDefaultSession().getCryptoVersion(context, true) + "\n"; jsonWriter.name("version").value(version); jsonWriter.endObject(); jsonWriter.close(); } catch (Exception e) { Log.e(LOG_TAG, "doInBackground ; failed to collect the bug report data " + e.getMessage()); serverError = e.getLocalizedMessage(); } catch (OutOfMemoryError oom) { Log.e(LOG_TAG, "doInBackground ; failed to collect the bug report data " + oom.getMessage()); serverError = oom.getMessage(); if (TextUtils.isEmpty(serverError)) { serverError = "Out of memory"; } } try { if (null != fileWriter) { fileWriter.close(); } } catch (Exception e) { Log.e(LOG_TAG, "doInBackground ; failed to close fileWriter " + e.getMessage()); } if (TextUtils.isEmpty(serverError) && !mIsCancelled) { // the screenshot is defined here // File screenFile = new File(VectorApp.mLogsDirectoryFile, "screenshot.jpg"); InputStream inputStream = null; HttpURLConnection conn = null; try { inputStream = new FileInputStream(bugReportFile); final int dataLen = inputStream.available(); // should never happen if (0 == dataLen) { return "No data"; } URL url = new URL(context.getResources().getString(R.string.bug_report_url)); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Content-Length", Integer.toString(dataLen)); // avoid caching data before really sending them. conn.setFixedLengthStreamingMode(inputStream.available()); conn.connect(); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); byte[] buffer = new byte[8192]; // read file and write it into form... int bytesRead; int totalWritten = 0; while (!mIsCancelled && (bytesRead = inputStream.read(buffer, 0, buffer.length)) > 0) { dos.write(buffer, 0, bytesRead); totalWritten += bytesRead; publishProgress(totalWritten * 100 / dataLen); } dos.flush(); dos.close(); int mResponseCode; try { // Read the SERVER RESPONSE mResponseCode = conn.getResponseCode(); } catch (EOFException eofEx) { mResponseCode = HttpURLConnection.HTTP_INTERNAL_ERROR; } // if the upload failed, try to retrieve the reason if (mResponseCode != HttpURLConnection.HTTP_OK) { serverError = null; InputStream is = conn.getErrorStream(); if (null != is) { int ch; StringBuilder b = new StringBuilder(); while ((ch = is.read()) != -1) { b.append((char) ch); } serverError = b.toString(); is.close(); // check if the error message try { JSONObject responseJSON = new JSONObject(serverError); serverError = responseJSON.getString("error"); } catch (JSONException e) { Log.e(LOG_TAG, "doInBackground ; Json conversion failed " + e.getMessage()); } // should never happen if (null == serverError) { serverError = "Failed with error " + mResponseCode; } is.close(); } } } catch (Exception e) { Log.e(LOG_TAG, "doInBackground ; failed with error " + e.getClass() + " - " + e.getMessage()); serverError = e.getLocalizedMessage(); if (TextUtils.isEmpty(serverError)) { serverError = "Failed to upload"; } } catch (OutOfMemoryError oom) { Log.e(LOG_TAG, "doInBackground ; failed to send the bug report " + oom.getMessage()); serverError = oom.getLocalizedMessage(); if (TextUtils.isEmpty(serverError)) { serverError = "Out ouf memory"; } } finally { try { if (null != conn) { conn.disconnect(); } } catch (Exception e2) { Log.e(LOG_TAG, "doInBackground : conn.disconnect() failed " + e2.getMessage()); } } if (null != inputStream) { try { inputStream.close(); } catch (Exception e) { Log.e(LOG_TAG, "doInBackground ; failed to close the inputStream " + e.getMessage()); } } } return serverError; } @Override protected void onProgressUpdate(Integer... progress) { super.onProgressUpdate(progress); if (null != listener) { try { listener.onProgress((null == progress) ? 0 : progress[0]); } catch (Exception e) { Log.e(LOG_TAG, "## onProgress() : failed " + e.getMessage()); } } } @Override protected void onPostExecute(String reason) { if (null != listener) { try { if (mIsCancelled) { listener.onUploadCancelled(); } else if (null == reason) { listener.onUploadSucceed(); } else { listener.onUploadFailed(reason); } } catch (Exception e) { Log.e(LOG_TAG, "## onPostExecute() : failed " + e.getMessage()); } } } }.execute(); }