Example usage for java.lang OutOfMemoryError getMessage

List of usage examples for java.lang OutOfMemoryError getMessage

Introduction

In this page you can find the example usage for java.lang OutOfMemoryError getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.elasticsearch.index.engine.internal.InternalEngine.java

@Override
public void optimize(Optimize optimize) throws EngineException {
    if (optimize.flush()) {
        flush(new Flush().force(true).waitIfOngoing(true));
    }/*ww w  . j  a v a2  s  . c  o  m*/
    if (optimizeMutex.compareAndSet(false, true)) {
        rwl.readLock().lock();
        try {
            ensureOpen();
            if (optimize.onlyExpungeDeletes()) {
                Merges.forceMergeDeletes(indexWriter, false);
            } else if (optimize.maxNumSegments() <= 0) {
                Merges.maybeMerge(indexWriter);
                possibleMergeNeeded = false;
            } else {
                Merges.forceMerge(indexWriter, optimize.maxNumSegments(), false);
            }
        } catch (OutOfMemoryError e) {
            failEngine(e);
            throw new OptimizeFailedEngineException(shardId, e);
        } catch (IllegalStateException e) {
            if (e.getMessage().contains("OutOfMemoryError")) {
                failEngine(e);
            }
            throw new OptimizeFailedEngineException(shardId, e);
        } catch (Throwable e) {
            throw new OptimizeFailedEngineException(shardId, e);
        } finally {
            rwl.readLock().unlock();
            optimizeMutex.set(false);
        }
    }
    // wait for the merges outside of the read lock
    if (optimize.waitForMerge()) {
        indexWriter.waitForMerges();
    }
    if (optimize.flush()) {
        flush(new Flush().force(true).waitIfOngoing(true));
    }
}

From source file:mobisocial.musubi.util.UriImage.java

/**
 * Returns the bytes for this UriImage. If the uri for the image is remote,
 * then this code must not be run on the main thread.
 *//*from ww  w  .ja v a  2s.  c om*/
public byte[] getResizedImageData(int widthLimit, int heightLimit, int byteLimit, boolean square)
        throws IOException {
    if (!mDecodedBounds) {
        decodeBoundsInfo();
        mDecodedBounds = true;
    }
    InputStream input = null;
    try {
        int inDensity = 0;
        int targetDensity = 0;
        BitmapFactory.Options read_options = new BitmapFactory.Options();
        read_options.inJustDecodeBounds = true;
        input = openInputStream(mUri);
        BitmapFactory.decodeStream(input, null, read_options);
        if (read_options.outWidth > widthLimit || read_options.outHeight > heightLimit) {
            //we need to scale
            if (read_options.outWidth / widthLimit > read_options.outHeight / heightLimit) {
                //width is the large edge
                if (read_options.outWidth * heightLimit > widthLimit * read_options.outHeight) {
                    //incoming image is wider than target
                    inDensity = read_options.outWidth;
                    targetDensity = widthLimit;
                } else {
                    //incoming image is taller than target
                    inDensity = read_options.outHeight;
                    targetDensity = heightLimit;

                }
            } else {
                //height is the long edge, swap the limits
                if (read_options.outWidth * widthLimit > heightLimit * read_options.outHeight) {
                    //incoming image is wider than target
                    inDensity = read_options.outWidth;
                    targetDensity = heightLimit;
                } else {
                    //incoming image is taller than target
                    inDensity = read_options.outHeight;
                    targetDensity = widthLimit;

                }
            }
        } else {
            //no scale
            if (read_options.outWidth > read_options.outHeight) {
                inDensity = targetDensity = read_options.outWidth;
            } else {
                inDensity = targetDensity = read_options.outHeight;
            }
        }

        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG,
                    "getResizedImageData: wlimit=" + widthLimit + ", hlimit=" + heightLimit + ", sizeLimit="
                            + byteLimit + ", mWidth=" + mWidth + ", mHeight=" + mHeight + ", initialRatio="
                            + targetDensity + "/" + inDensity);
        }

        ByteArrayOutputStream os = null;
        int attempts = 1;

        int lowMemoryReduce = 1;
        do {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inDensity = inDensity;
            options.inSampleSize = lowMemoryReduce;
            options.inScaled = lowMemoryReduce == 1;
            options.inTargetDensity = targetDensity;
            //no purgeable because we are only trying to resave this
            if (input != null)
                input.close();
            input = openInputStream(mUri);
            int quality = IMAGE_COMPRESSION_QUALITY;
            try {
                Bitmap b = BitmapFactory.decodeStream(input, null, options);
                if (b == null) {
                    return null;
                }
                if (options.outWidth > widthLimit + 1 || options.outHeight > heightLimit + 1) {
                    // The decoder does not support the inSampleSize option.
                    // Scale the bitmap using Bitmap library.
                    int scaledWidth;
                    int scaledHeight;
                    scaledWidth = options.outWidth * targetDensity / inDensity;
                    scaledHeight = options.outHeight * targetDensity / inDensity;

                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
                        Log.v(TAG, "getResizedImageData: retry scaling using " + "Bitmap.createScaledBitmap: w="
                                + scaledWidth + ", h=" + scaledHeight);
                    }

                    if (square) {
                        int w = b.getWidth();
                        int h = b.getHeight();
                        int dim = Math.min(w, h);
                        b = Bitmap.createBitmap(b, (w - dim) / 2, (h - dim) / 2, dim, dim);
                        scaledWidth = dim;
                        scaledHeight = dim;
                    }
                    Bitmap b2 = Bitmap.createScaledBitmap(b, scaledWidth, scaledHeight, false);
                    b.recycle();
                    b = b2;
                    if (b == null) {
                        return null;
                    }
                }

                Matrix matrix = new Matrix();
                if (mRotation != 0f) {
                    matrix.preRotate(mRotation);
                }

                Bitmap old = b;
                b = Bitmap.createBitmap(old, 0, 0, old.getWidth(), old.getHeight(), matrix, true);

                // Compress the image into a JPG. Start with MessageUtils.IMAGE_COMPRESSION_QUALITY.
                // In case that the image byte size is still too large reduce the quality in
                // proportion to the desired byte size. Should the quality fall below
                // MINIMUM_IMAGE_COMPRESSION_QUALITY skip a compression attempt and we will enter
                // the next round with a smaller image to start with.
                os = new ByteArrayOutputStream();
                b.compress(CompressFormat.JPEG, quality, os);
                int jpgFileSize = os.size();
                if (jpgFileSize > byteLimit) {
                    int reducedQuality = quality * byteLimit / jpgFileSize;
                    //always try to squish it before computing the new size
                    if (reducedQuality < MINIMUM_IMAGE_COMPRESSION_QUALITY) {
                        reducedQuality = MINIMUM_IMAGE_COMPRESSION_QUALITY;
                    }
                    quality = reducedQuality;

                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
                        Log.v(TAG, "getResizedImageData: compress(2) w/ quality=" + quality);
                    }

                    os = new ByteArrayOutputStream();
                    b.compress(CompressFormat.JPEG, quality, os);
                }
                b.recycle(); // done with the bitmap, release the memory
            } catch (java.lang.OutOfMemoryError e) {
                Log.w(TAG, "getResizedImageData - image too big (OutOfMemoryError), will try "
                        + " with smaller scale factor, cur scale factor", e);
                lowMemoryReduce *= 2;
                // fall through and keep trying with a smaller scale factor.
            }
            if (true || Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG,
                        "attempt=" + attempts + " size=" + (os == null ? 0 : os.size()) + " width="
                                + options.outWidth + " height=" + options.outHeight + " Ratio=" + targetDensity
                                + "/" + inDensity + " quality=" + quality);
            }
            //move halfway to the target
            targetDensity = (os == null) ? (int) (targetDensity * .8)
                    : (targetDensity * byteLimit / os.size() + targetDensity) / 2;
            attempts++;
        } while ((os == null || os.size() > byteLimit) && attempts < NUMBER_OF_RESIZE_ATTEMPTS);

        return os == null ? null : os.toByteArray();
    } catch (Throwable t) {
        Log.e(TAG, t.getMessage(), t);
        return null;
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                Log.e(TAG, e.getMessage(), e);
            }
        }
    }
}

From source file:net.sf.ehcache.CacheTest.java

License:asdf

/**
 * Shows the effect of jamming large amounts of puts into a cache that overflows to disk.
 * The DiskStore should cause puts to back off and avoid an out of memory error.
 *///from  w w w .  j a v a2s.  c om
public void testBehaviourOnDiskStoreBackUp() throws Exception {
    Cache cache = new Cache("testGetMemoryStoreSize", 10, true, false, 100, 200, false, 0);
    manager.addCache(cache);

    assertEquals(0, cache.getMemoryStoreSize());

    Element a = null;
    int i = 0;
    try {
        for (; i < 200000; i++) {
            String key = i + "";
            String value = key;
            a = new Element(key,
                    value + "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD");
            cache.put(a);
        }
    } catch (OutOfMemoryError e) {
        LOG.info("OutOfMemoryError: " + e.getMessage() + " " + i);
        fail();
    }
}

From source file:org.elasticsearch.test.ESIntegTestCase.java

protected final void beforeInternal() throws Exception {
    assert Thread.getDefaultUncaughtExceptionHandler() instanceof ElasticsearchUncaughtExceptionHandler;
    try {/*  w ww. j a v a  2  s .com*/
        final Scope currentClusterScope = getCurrentClusterScope();
        switch (currentClusterScope) {
        case SUITE:
            assert SUITE_SEED != null : "Suite seed was not initialized";
            currentCluster = buildAndPutCluster(currentClusterScope, SUITE_SEED);
            break;
        case TEST:
            currentCluster = buildAndPutCluster(currentClusterScope, randomLong());
            break;
        default:
            fail("Unknown Scope: [" + currentClusterScope + "]");
        }
        cluster().beforeTest(getRandom(), getPerTestTransportClientRatio());
        cluster().wipe();
        randomIndexTemplate();
        printTestMessage("before");
    } catch (OutOfMemoryError e) {
        if (e.getMessage().contains("unable to create new native thread")) {
            ESTestCase.printStackDump(logger);
        }
        throw e;
    }
}

From source file:im.vector.activity.RoomActivity.java

/**
 * Send a list of images from their URIs
 * @param mediaUris the media URIs//  w w  w  .j  ava2  s. c om
 */
private void sendMedias(final ArrayList<Uri> mediaUris) {

    final View progressBackground = findViewById(R.id.medias_processing_progress_background);
    final View progress = findViewById(R.id.medias_processing_progress);

    progressBackground.setVisibility(View.VISIBLE);
    progress.setVisibility(View.VISIBLE);

    final HandlerThread handlerThread = new HandlerThread("MediasEncodingThread");
    handlerThread.start();

    final android.os.Handler handler = new android.os.Handler(handlerThread.getLooper());

    Runnable r = new Runnable() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    final int mediaCount = mediaUris.size();

                    for (Uri anUri : mediaUris) {
                        // crash from Google Analytics : null URI on a nexus 5
                        if (null != anUri) {
                            final Uri mediaUri = anUri;
                            String filename = null;

                            if (mediaUri.toString().startsWith("content://")) {
                                Cursor cursor = null;
                                try {
                                    cursor = RoomActivity.this.getContentResolver().query(mediaUri, null, null,
                                            null, null);
                                    if (cursor != null && cursor.moveToFirst()) {
                                        filename = cursor
                                                .getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                                    }
                                } catch (Exception e) {
                                    Log.e(LOG_TAG, "cursor.getString " + e.getMessage());
                                } finally {
                                    cursor.close();
                                }

                                if (TextUtils.isEmpty(filename)) {
                                    List uriPath = mediaUri.getPathSegments();
                                    filename = (String) uriPath.get(uriPath.size() - 1);
                                }
                            } else if (mediaUri.toString().startsWith("file://")) {
                                // try to retrieve the filename from the file url.
                                try {
                                    filename = anUri.getLastPathSegment();
                                } catch (Exception e) {
                                }

                                if (TextUtils.isEmpty(filename)) {
                                    filename = null;
                                }
                            }

                            final String fFilename = filename;

                            ResourceUtils.Resource resource = ResourceUtils.openResource(RoomActivity.this,
                                    mediaUri);

                            if (null == resource) {
                                RoomActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        handlerThread.quit();
                                        progressBackground.setVisibility(View.GONE);
                                        progress.setVisibility(View.GONE);

                                        Toast.makeText(RoomActivity.this,
                                                getString(R.string.message_failed_to_upload), Toast.LENGTH_LONG)
                                                .show();
                                    }

                                    ;
                                });

                                return;
                            }

                            // save the file in the filesystem
                            String mediaUrl = mMediasCache.saveMedia(resource.contentStream, null,
                                    resource.mimeType);
                            String mimeType = resource.mimeType;
                            Boolean isManaged = false;

                            if ((null != resource.mimeType) && resource.mimeType.startsWith("image/")) {
                                // manage except if there is an error
                                isManaged = true;

                                // try to retrieve the gallery thumbnail
                                // if the image comes from the gallery..
                                Bitmap thumbnailBitmap = null;

                                try {
                                    ContentResolver resolver = getContentResolver();

                                    List uriPath = mediaUri.getPathSegments();
                                    long imageId = -1;
                                    String lastSegment = (String) uriPath.get(uriPath.size() - 1);

                                    // > Kitkat
                                    if (lastSegment.startsWith("image:")) {
                                        lastSegment = lastSegment.substring("image:".length());
                                    }

                                    imageId = Long.parseLong(lastSegment);

                                    thumbnailBitmap = MediaStore.Images.Thumbnails.getThumbnail(resolver,
                                            imageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
                                } catch (Exception e) {
                                    Log.e(LOG_TAG,
                                            "MediaStore.Images.Thumbnails.getThumbnail " + e.getMessage());
                                }

                                double thumbnailWidth = mConsoleMessageListFragment.getMaxThumbnailWith();
                                double thumbnailHeight = mConsoleMessageListFragment.getMaxThumbnailHeight();

                                // no thumbnail has been found or the mimetype is unknown
                                if ((null == thumbnailBitmap) || (thumbnailBitmap.getHeight() > thumbnailHeight)
                                        || (thumbnailBitmap.getWidth() > thumbnailWidth)) {
                                    // need to decompress the high res image
                                    BitmapFactory.Options options = new BitmapFactory.Options();
                                    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                                    resource = ResourceUtils.openResource(RoomActivity.this, mediaUri);

                                    // get the full size bitmap
                                    Bitmap fullSizeBitmap = null;

                                    if (null == thumbnailBitmap) {
                                        fullSizeBitmap = BitmapFactory.decodeStream(resource.contentStream,
                                                null, options);
                                    }

                                    if ((fullSizeBitmap != null) || (thumbnailBitmap != null)) {
                                        double imageWidth;
                                        double imageHeight;

                                        if (null == thumbnailBitmap) {
                                            imageWidth = fullSizeBitmap.getWidth();
                                            imageHeight = fullSizeBitmap.getHeight();
                                        } else {
                                            imageWidth = thumbnailBitmap.getWidth();
                                            imageHeight = thumbnailBitmap.getHeight();
                                        }

                                        if (imageWidth > imageHeight) {
                                            thumbnailHeight = thumbnailWidth * imageHeight / imageWidth;
                                        } else {
                                            thumbnailWidth = thumbnailHeight * imageWidth / imageHeight;
                                        }

                                        try {
                                            thumbnailBitmap = Bitmap.createScaledBitmap(
                                                    (null == fullSizeBitmap) ? thumbnailBitmap : fullSizeBitmap,
                                                    (int) thumbnailWidth, (int) thumbnailHeight, false);
                                        } catch (OutOfMemoryError ex) {
                                            Log.e(LOG_TAG, "Bitmap.createScaledBitmap " + ex.getMessage());
                                        }
                                    }

                                    // the valid mimetype is not provided
                                    if ("image/*".equals(mimeType)) {
                                        // make a jpg snapshot.
                                        mimeType = null;
                                    }

                                    // unknown mimetype
                                    if ((null == mimeType) || (mimeType.startsWith("image/"))) {
                                        try {
                                            // try again
                                            if (null == fullSizeBitmap) {
                                                System.gc();
                                                fullSizeBitmap = BitmapFactory
                                                        .decodeStream(resource.contentStream, null, options);
                                            }

                                            if (null != fullSizeBitmap) {
                                                Uri uri = Uri.parse(mediaUrl);

                                                if (null == mimeType) {
                                                    // the images are save in jpeg format
                                                    mimeType = "image/jpeg";
                                                }

                                                resource.contentStream.close();
                                                resource = ResourceUtils.openResource(RoomActivity.this,
                                                        mediaUri);

                                                try {
                                                    mMediasCache.saveMedia(resource.contentStream,
                                                            uri.getPath(), mimeType);
                                                } catch (OutOfMemoryError ex) {
                                                    Log.e(LOG_TAG, "mMediasCache.saveMedia" + ex.getMessage());
                                                }

                                            } else {
                                                isManaged = false;
                                            }

                                            resource.contentStream.close();

                                        } catch (Exception e) {
                                            isManaged = false;
                                            Log.e(LOG_TAG, "sendMedias " + e.getMessage());
                                        }
                                    }

                                    // reduce the memory consumption
                                    if (null != fullSizeBitmap) {
                                        fullSizeBitmap.recycle();
                                        System.gc();
                                    }
                                }

                                String thumbnailURL = mMediasCache.saveBitmap(thumbnailBitmap, null);

                                if (null != thumbnailBitmap) {
                                    thumbnailBitmap.recycle();
                                }

                                //
                                if (("image/jpg".equals(mimeType) || "image/jpeg".equals(mimeType))
                                        && (null != mediaUrl)) {

                                    Uri imageUri = Uri.parse(mediaUrl);
                                    // get the exif rotation angle
                                    final int rotationAngle = ImageUtils
                                            .getRotationAngleForBitmap(RoomActivity.this, imageUri);

                                    if (0 != rotationAngle) {
                                        // always apply the rotation to the image
                                        ImageUtils.rotateImage(RoomActivity.this, thumbnailURL, rotationAngle,
                                                mMediasCache);

                                        // the high res media orientation should be not be done on uploading
                                        //ImageUtils.rotateImage(RoomActivity.this, mediaUrl, rotationAngle, mMediasCache))
                                    }
                                }

                                // is the image content valid ?
                                if (isManaged && (null != thumbnailURL)) {

                                    final String fThumbnailURL = thumbnailURL;
                                    final String fMediaUrl = mediaUrl;
                                    final String fMimeType = mimeType;

                                    RoomActivity.this.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            // if there is only one image
                                            if (mediaCount == 1) {
                                                // display an image preview before sending it
                                                mPendingThumbnailUrl = fThumbnailURL;
                                                mPendingMediaUrl = fMediaUrl;
                                                mPendingMimeType = fMimeType;
                                                mPendingFilename = fFilename;

                                                mConsoleMessageListFragment.scrollToBottom();

                                                manageSendMoreButtons();
                                            } else {
                                                mConsoleMessageListFragment.uploadImageContent(fThumbnailURL,
                                                        fMediaUrl, fFilename, fMimeType);
                                            }
                                        }
                                    });
                                }
                            }

                            // default behaviour
                            if ((!isManaged) && (null != mediaUrl)) {
                                final String fMediaUrl = mediaUrl;
                                final String fMimeType = mimeType;

                                RoomActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mConsoleMessageListFragment.uploadMediaContent(fMediaUrl, fMimeType,
                                                fFilename);
                                    }
                                });
                            }
                        }
                    }

                    RoomActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            handlerThread.quit();
                            progressBackground.setVisibility(View.GONE);
                            progress.setVisibility(View.GONE);
                        };
                    });
                }
            });
        }
    };

    Thread t = new Thread(r);
    t.start();
}

From source file:org.elasticsearch.index.engine.internal.InternalEngine.java

@Override
public void flush(Flush flush) throws EngineException {
    ensureOpen();/*  w w  w .  j a v a 2 s  .  c  o  m*/
    if (flush.type() == Flush.Type.NEW_WRITER || flush.type() == Flush.Type.COMMIT_TRANSLOG) {
        // check outside the lock as well so we can check without blocking on the write lock
        if (onGoingRecoveries.get() > 0) {
            throw new FlushNotAllowedEngineException(shardId,
                    "recovery is in progress, flush [" + flush.type() + "] is not allowed");
        }
    }
    int currentFlushing = flushing.incrementAndGet();
    if (currentFlushing > 1 && !flush.waitIfOngoing()) {
        flushing.decrementAndGet();
        throw new FlushNotAllowedEngineException(shardId, "already flushing...");
    }

    flushLock.lock();
    try {
        if (flush.type() == Flush.Type.NEW_WRITER) {
            rwl.writeLock().lock();
            try {
                ensureOpen();
                if (onGoingRecoveries.get() > 0) {
                    throw new FlushNotAllowedEngineException(shardId,
                            "Recovery is in progress, flush is not allowed");
                }
                // disable refreshing, not dirty
                dirty = false;
                try {
                    // that's ok if the index writer failed and is in inconsistent state
                    // we will get an exception on a dirty operation, and will cause the shard
                    // to be allocated to a different node
                    indexWriter.close(false);
                    indexWriter = createWriter();
                    // if(features ! = null)
                    // {
                    indexWriter.features = features;
                    if (features.size() == 0) {
                        fillHashMap();
                    }
                    // }
                    // commit on a just opened writer will commit even if there are no changes done to it
                    // we rely on that for the commit data translog id key
                    if (flushNeeded || flush.force()) {
                        flushNeeded = false;
                        long translogId = translogIdGenerator.incrementAndGet();
                        indexWriter.setCommitData(MapBuilder.<String, String>newMapBuilder()
                                .put(Translog.TRANSLOG_ID_KEY, Long.toString(translogId)).map());
                        indexWriter.commit();
                        translog.newTranslog(translogId);
                    }

                    SearcherManager current = this.searcherManager;
                    this.searcherManager = buildSearchManager(indexWriter);
                    try {
                        IOUtils.close(current);
                    } catch (Throwable t) {
                        logger.warn("Failed to close current SearcherManager", t);
                    }
                    refreshVersioningTable(threadPool.estimatedTimeInMillis());
                } catch (OutOfMemoryError e) {
                    failEngine(e);
                    throw new FlushFailedEngineException(shardId, e);
                } catch (IllegalStateException e) {
                    if (e.getMessage().contains("OutOfMemoryError")) {
                        failEngine(e);
                    }
                    throw new FlushFailedEngineException(shardId, e);
                } catch (Throwable e) {
                    throw new FlushFailedEngineException(shardId, e);
                }
            } finally {
                rwl.writeLock().unlock();
            }
        } else if (flush.type() == Flush.Type.COMMIT_TRANSLOG) {
            rwl.readLock().lock();
            try {
                ensureOpen();
                if (onGoingRecoveries.get() > 0) {
                    throw new FlushNotAllowedEngineException(shardId,
                            "Recovery is in progress, flush is not allowed");
                }

                if (flushNeeded || flush.force()) {
                    flushNeeded = false;
                    try {
                        long translogId = translogIdGenerator.incrementAndGet();
                        translog.newTransientTranslog(translogId);
                        indexWriter.setCommitData(MapBuilder.<String, String>newMapBuilder()
                                .put(Translog.TRANSLOG_ID_KEY, Long.toString(translogId)).map());
                        indexWriter.commit();
                        refreshVersioningTable(threadPool.estimatedTimeInMillis());
                        // we need to move transient to current only after we refresh
                        // so items added to current will still be around for realtime get
                        // when tans overrides it
                        translog.makeTransientCurrent();
                    } catch (OutOfMemoryError e) {
                        translog.revertTransient();
                        failEngine(e);
                        throw new FlushFailedEngineException(shardId, e);
                    } catch (IllegalStateException e) {
                        if (e.getMessage().contains("OutOfMemoryError")) {
                            failEngine(e);
                        }
                        throw new FlushFailedEngineException(shardId, e);
                    } catch (Throwable e) {
                        translog.revertTransient();
                        throw new FlushFailedEngineException(shardId, e);
                    }
                }
            } finally {
                rwl.readLock().unlock();
            }
        } else if (flush.type() == Flush.Type.COMMIT) {
            // note, its ok to just commit without cleaning the translog, its perfectly fine to replay a
            // translog on an index that was opened on a committed point in time that is "in the future"
            // of that translog
            rwl.readLock().lock();
            try {
                ensureOpen();
                // we allow to *just* commit if there is an ongoing recovery happening...
                // its ok to use this, only a flush will cause a new translogId, and we are locked here from
                // other flushes use flushLock
                try {
                    long translogId = translog.currentId();
                    indexWriter.setCommitData(MapBuilder.<String, String>newMapBuilder()
                            .put(Translog.TRANSLOG_ID_KEY, Long.toString(translogId)).map());
                    indexWriter.commit();
                } catch (OutOfMemoryError e) {
                    translog.revertTransient();
                    failEngine(e);
                    throw new FlushFailedEngineException(shardId, e);
                } catch (IllegalStateException e) {
                    if (e.getMessage().contains("OutOfMemoryError")) {
                        failEngine(e);
                    }
                    throw new FlushFailedEngineException(shardId, e);
                } catch (Throwable e) {
                    throw new FlushFailedEngineException(shardId, e);
                }
            } finally {
                rwl.readLock().unlock();
            }
        } else {
            throw new ElasticsearchIllegalStateException("flush type [" + flush.type() + "] not supported");
        }

        // reread the last committed segment infos
        rwl.readLock().lock();
        try {
            ensureOpen();
            readLastCommittedSegmentsInfo();
        } catch (Throwable e) {
            if (!closed) {
                logger.warn("failed to read latest segment infos on flush", e);
            }
        } finally {
            rwl.readLock().unlock();
        }

    } finally {
        flushLock.unlock();
        flushing.decrementAndGet();
    }
}

From source file:org.elasticsearch.test.ElasticsearchIntegrationTest.java

protected final void beforeInternal() throws Exception {
    assert Thread.getDefaultUncaughtExceptionHandler() instanceof ElasticsearchUncaughtExceptionHandler;
    try {//w ww .j a  v  a 2s . co m
        final Scope currentClusterScope = getCurrentClusterScope();
        switch (currentClusterScope) {
        case SUITE:
            assert SUITE_SEED != null : "Suite seed was not initialized";
            currentCluster = buildAndPutCluster(currentClusterScope, SUITE_SEED);
            break;
        case TEST:
            currentCluster = buildAndPutCluster(currentClusterScope, randomLong());
            break;
        default:
            fail("Unknown Scope: [" + currentClusterScope + "]");
        }
        cluster().beforeTest(getRandom(), getPerTestTransportClientRatio());
        cluster().wipe();
        randomIndexTemplate();
        printTestMessage("before");
    } catch (OutOfMemoryError e) {
        if (e.getMessage().contains("unable to create new native thread")) {
            ElasticsearchTestCase.printStackDump(logger);
        }
        throw e;
    }
}

From source file:org.yamj.core.service.artwork.ArtworkProcessorService.java

private void generateImage(ArtworkLocated located, ArtworkProfile profile) throws Exception {
    StorageType storageType;/*from  w  w  w .  j a v  a2 s .c  o m*/
    if (located.getArtwork().getArtworkType() == ArtworkType.PHOTO) {
        storageType = StorageType.PHOTO;
    } else {
        storageType = StorageType.ARTWORK;
    }

    LOG.debug("Generate image for {} with profile {}", located, profile.getProfileName());
    BufferedImage imageGraphic = null;
    try {
        imageGraphic = GraphicTools
                .loadJPEGImage(this.fileStorageService.getFile(storageType, located.getCacheFilename()));
    } catch (OutOfMemoryError ex) {
        LOG.error("Failed to load/transform image '{}' due to memory constraints", located.getCacheFilename());
    }

    if (imageGraphic == null) {
        LOG.error("Error processing image '{}', not processed further.", located.getCacheFilename());
        // Mark the image as unprocessable
        located.setStatus(StatusType.ERROR);
        artworkStorageService.updateArtworkLocated(located);
        // quit
        return;
    }

    // set dimension of original image if not done before
    if (located.getWidth() <= 0 || located.getHeight() <= 0) {
        located.setWidth(imageGraphic.getWidth());
        located.setHeight(imageGraphic.getHeight());
    }

    // draw the image
    BufferedImage image = drawImage(imageGraphic, profile);

    // store image on stage system
    String cacheFilename = buildCacheFilename(located, profile);
    fileStorageService.storeImage(cacheFilename, storageType, image, profile.getImageFormat(),
            profile.getQuality());

    try {
        ArtworkGenerated generated = new ArtworkGenerated();
        generated.setArtworkLocated(located);
        generated.setArtworkProfile(profile);
        generated.setCacheFilename(cacheFilename);
        String cacheDirectory = FileTools.createDirHash(cacheFilename);
        generated.setCacheDirectory(StringUtils.removeEnd(cacheDirectory, File.separator + cacheFilename));
        artworkStorageService.storeArtworkGenerated(generated);
    } catch (Exception ex) {
        // delete generated file storage element also
        LOG.trace("Failed to generate file storage for {}, error: {}", cacheFilename, ex.getMessage());
        try {
            fileStorageService.delete(storageType, cacheFilename);
        } catch (IOException ex2) {
            LOG.trace("Unable to delete file after exception: {}", ex2.getMessage(), ex);
        }
        throw ex;
    }
}

From source file:im.vector.activity.RoomActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    if (CommonActivityUtils.shouldRestartApp()) {
        Log.e(LOG_TAG, "Restart the application.");
        CommonActivityUtils.restartApp(this);
    }/*w  w  w  . j  a  v a 2s  .  c o m*/

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_room);

    Intent intent = getIntent();
    if (!intent.hasExtra(EXTRA_ROOM_ID)) {
        Log.e(LOG_TAG, "No room ID extra.");
        finish();
        return;
    }

    // the user has tapped on the "View" notification button
    if ((null != intent.getAction()) && (intent.getAction().startsWith(NotificationUtils.TAP_TO_VIEW_ACTION))) {
        // remove any pending notifications
        NotificationManager notificationsManager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);
        notificationsManager.cancelAll();
    }

    mPendingThumbnailUrl = null;
    mPendingMediaUrl = null;
    mPendingMimeType = null;
    mPendingFilename = null;

    if (null != savedInstanceState) {
        if (savedInstanceState.containsKey(PENDING_THUMBNAIL_URL)) {
            mPendingThumbnailUrl = savedInstanceState.getString(PENDING_THUMBNAIL_URL);
        }

        if (savedInstanceState.containsKey(PENDING_MEDIA_URL)) {
            mPendingMediaUrl = savedInstanceState.getString(PENDING_MEDIA_URL);
        }

        if (savedInstanceState.containsKey(PENDING_MIMETYPE)) {
            mPendingMimeType = savedInstanceState.getString(PENDING_MIMETYPE);
        }

        if (savedInstanceState.containsKey(PENDING_FILENAME)) {
            mPendingFilename = savedInstanceState.getString(PENDING_FILENAME);
        }
    }

    String roomId = intent.getStringExtra(EXTRA_ROOM_ID);
    Log.i(LOG_TAG, "Displaying " + roomId);

    mEditText = (EditText) findViewById(R.id.editText_messageBox);

    mSendButton = (ImageButton) findViewById(R.id.button_send);
    mSendButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // send the previewed image ?
            if (null != mPendingThumbnailUrl) {
                boolean sendMedia = true;

                // check if the media could be resized
                if ("image/jpeg".equals(mPendingMimeType)) {

                    System.gc();
                    FileInputStream imageStream = null;

                    try {
                        Uri uri = Uri.parse(mPendingMediaUrl);
                        final String filename = uri.getPath();

                        final int rotationAngle = ImageUtils.getRotationAngleForBitmap(RoomActivity.this, uri);

                        imageStream = new FileInputStream(new File(filename));

                        int fileSize = imageStream.available();

                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inJustDecodeBounds = true;
                        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                        options.outWidth = -1;
                        options.outHeight = -1;

                        // get the full size bitmap
                        Bitmap fullSizeBitmap = null;
                        try {
                            fullSizeBitmap = BitmapFactory.decodeStream(imageStream, null, options);
                        } catch (OutOfMemoryError e) {
                            Log.e(LOG_TAG, "Onclick BitmapFactory.decodeStream : " + e.getMessage());
                        }

                        final ImageSize fullImageSize = new ImageSize(options.outWidth, options.outHeight);

                        imageStream.close();

                        int maxSide = (fullImageSize.mHeight > fullImageSize.mWidth) ? fullImageSize.mHeight
                                : fullImageSize.mWidth;

                        // can be rescaled ?
                        if (maxSide > SMALL_IMAGE_SIZE) {
                            ImageSize largeImageSize = null;

                            int divider = 2;

                            if (maxSide > LARGE_IMAGE_SIZE) {
                                largeImageSize = new ImageSize((fullImageSize.mWidth + (divider - 1)) / divider,
                                        (fullImageSize.mHeight + (divider - 1)) / divider);
                                divider *= 2;
                            }

                            ImageSize mediumImageSize = null;

                            if (maxSide > MEDIUM_IMAGE_SIZE) {
                                mediumImageSize = new ImageSize(
                                        (fullImageSize.mWidth + (divider - 1)) / divider,
                                        (fullImageSize.mHeight + (divider - 1)) / divider);
                                divider *= 2;
                            }

                            ImageSize smallImageSize = null;

                            if (maxSide > SMALL_IMAGE_SIZE) {
                                smallImageSize = new ImageSize((fullImageSize.mWidth + (divider - 1)) / divider,
                                        (fullImageSize.mHeight + (divider - 1)) / divider);
                            }

                            FragmentManager fm = getSupportFragmentManager();
                            ImageSizeSelectionDialogFragment fragment = (ImageSizeSelectionDialogFragment) fm
                                    .findFragmentByTag(TAG_FRAGMENT_IMAGE_SIZE_DIALOG);

                            if (fragment != null) {
                                fragment.dismissAllowingStateLoss();
                            }

                            final ArrayList<ImageCompressionDescription> textsList = new ArrayList<ImageCompressionDescription>();
                            final ArrayList<ImageSize> sizesList = new ArrayList<ImageSize>();

                            ImageCompressionDescription description = new ImageCompressionDescription();
                            description.mCompressionText = getString(R.string.compression_opt_list_original);
                            description.mCompressionInfoText = fullImageSize.mWidth + "x"
                                    + fullImageSize.mHeight + " ("
                                    + android.text.format.Formatter.formatFileSize(RoomActivity.this, fileSize)
                                    + ")";

                            textsList.add(description);
                            sizesList.add(fullImageSize);

                            if (null != largeImageSize) {
                                int estFileSize = largeImageSize.mWidth * largeImageSize.mHeight * 2 / 10 / 1024
                                        * 1024;

                                description = new ImageCompressionDescription();
                                description.mCompressionText = getString(R.string.compression_opt_list_large);
                                description.mCompressionInfoText = largeImageSize.mWidth + "x"
                                        + largeImageSize.mHeight + " (~" + android.text.format.Formatter
                                                .formatFileSize(RoomActivity.this, estFileSize)
                                        + ")";

                                textsList.add(description);
                                sizesList.add(largeImageSize);
                            }

                            if (null != mediumImageSize) {
                                int estFileSize = mediumImageSize.mWidth * mediumImageSize.mHeight * 2 / 10
                                        / 1024 * 1024;

                                description = new ImageCompressionDescription();
                                description.mCompressionText = getString(R.string.compression_opt_list_medium);
                                description.mCompressionInfoText = mediumImageSize.mWidth + "x"
                                        + mediumImageSize.mHeight + " (~" + android.text.format.Formatter
                                                .formatFileSize(RoomActivity.this, estFileSize)
                                        + ")";

                                textsList.add(description);
                                sizesList.add(mediumImageSize);
                            }

                            if (null != smallImageSize) {
                                int estFileSize = smallImageSize.mWidth * smallImageSize.mHeight * 2 / 10 / 1024
                                        * 1024;

                                description = new ImageCompressionDescription();
                                description.mCompressionText = getString(R.string.compression_opt_list_small);
                                description.mCompressionInfoText = smallImageSize.mWidth + "x"
                                        + smallImageSize.mHeight + " (~" + android.text.format.Formatter
                                                .formatFileSize(RoomActivity.this, estFileSize)
                                        + ")";

                                textsList.add(description);
                                sizesList.add(smallImageSize);
                            }

                            fragment = ImageSizeSelectionDialogFragment.newInstance(textsList);
                            fragment.setListener(new ImageSizeSelectionDialogFragment.ImageSizeListener() {
                                @Override
                                public void onSelected(int pos) {
                                    final int fPos = pos;

                                    RoomActivity.this.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                // pos == 0 -> original
                                                if (0 != fPos) {
                                                    FileInputStream imageStream = new FileInputStream(
                                                            new File(filename));

                                                    ImageSize imageSize = sizesList.get(fPos);
                                                    InputStream resizeBitmapStream = null;

                                                    try {
                                                        resizeBitmapStream = ImageUtils.resizeImage(imageStream,
                                                                -1,
                                                                (fullImageSize.mWidth + imageSize.mWidth - 1)
                                                                        / imageSize.mWidth,
                                                                75);
                                                    } catch (OutOfMemoryError ex) {
                                                        Log.e(LOG_TAG,
                                                                "Onclick BitmapFactory.createScaledBitmap : "
                                                                        + ex.getMessage());
                                                    } catch (Exception e) {
                                                        Log.e(LOG_TAG,
                                                                "Onclick BitmapFactory.createScaledBitmap failed : "
                                                                        + e.getMessage());
                                                    }

                                                    if (null != resizeBitmapStream) {
                                                        String bitmapURL = mMediasCache.saveMedia(
                                                                resizeBitmapStream, null, "image/jpeg");

                                                        if (null != bitmapURL) {
                                                            mPendingMediaUrl = bitmapURL;
                                                        }

                                                        resizeBitmapStream.close();

                                                        // try to apply exif rotation
                                                        if (0 != rotationAngle) {
                                                            // rotate the image content
                                                            ImageUtils.rotateImage(RoomActivity.this,
                                                                    mPendingMediaUrl, rotationAngle,
                                                                    mMediasCache);
                                                        }
                                                    }
                                                }
                                            } catch (Exception e) {
                                                Log.e(LOG_TAG, "Onclick " + e.getMessage());
                                            }

                                            //
                                            mConsoleMessageListFragment.uploadImageContent(mPendingThumbnailUrl,
                                                    mPendingMediaUrl, mPendingFilename, mPendingMimeType);
                                            mPendingThumbnailUrl = null;
                                            mPendingMediaUrl = null;
                                            mPendingMimeType = null;
                                            mPendingFilename = null;
                                            manageSendMoreButtons();
                                        }
                                    });
                                }
                            });

                            fragment.show(fm, TAG_FRAGMENT_IMAGE_SIZE_DIALOG);
                            sendMedia = false;
                        }

                    } catch (Exception e) {
                        Log.e(LOG_TAG, "Onclick " + e.getMessage());
                    }
                }

                if (sendMedia) {
                    mConsoleMessageListFragment.uploadImageContent(mPendingThumbnailUrl, mPendingMediaUrl,
                            mPendingFilename, mPendingMimeType);
                    mPendingThumbnailUrl = null;
                    mPendingMediaUrl = null;
                    mPendingMimeType = null;
                    mPendingFilename = null;
                    manageSendMoreButtons();
                }
            } else {
                String body = mEditText.getText().toString();
                sendMessage(body);
                mEditText.setText("");
            }
        }
    });

    mAttachmentButton = (ImageButton) findViewById(R.id.button_more);
    mAttachmentButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            FragmentManager fm = getSupportFragmentManager();
            IconAndTextDialogFragment fragment = (IconAndTextDialogFragment) fm
                    .findFragmentByTag(TAG_FRAGMENT_ATTACHMENTS_DIALOG);

            if (fragment != null) {
                fragment.dismissAllowingStateLoss();
            }

            final Integer[] messages = new Integer[] { R.string.option_send_files,
                    R.string.option_take_photo, };

            final Integer[] icons = new Integer[] { R.drawable.ic_material_file, // R.string.option_send_files
                    R.drawable.ic_material_camera, // R.string.action_members
            };

            fragment = IconAndTextDialogFragment.newInstance(icons, messages, null,
                    RoomActivity.this.getResources().getColor(R.color.vector_title_color));
            fragment.setOnClickListener(new IconAndTextDialogFragment.OnItemClickListener() {
                @Override
                public void onItemClick(IconAndTextDialogFragment dialogFragment, int position) {
                    Integer selectedVal = messages[position];

                    if (selectedVal == R.string.option_send_files) {
                        RoomActivity.this.launchFileSelectionIntent();
                    } else if (selectedVal == R.string.option_take_photo) {
                        RoomActivity.this.launchCamera();
                    }
                }
            });

            fragment.show(fm, TAG_FRAGMENT_INVITATION_MEMBERS_DIALOG);
        }
    });

    mEditText.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(android.text.Editable s) {
            MXLatestChatMessageCache latestChatMessageCache = RoomActivity.this.mLatestChatMessageCache;

            String textInPlace = latestChatMessageCache.getLatestText(RoomActivity.this, mRoom.getRoomId());

            // check if there is really an update
            // avoid useless updates (initializations..)
            if (!mIgnoreTextUpdate && !textInPlace.equals(mEditText.getText().toString())) {
                latestChatMessageCache.updateLatestMessage(RoomActivity.this, mRoom.getRoomId(),
                        mEditText.getText().toString());
                handleTypingNotification(mEditText.getText().length() != 0);
            }

            manageSendMoreButtons();
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    mSession = getSession(intent);

    if (mSession == null) {
        Log.e(LOG_TAG, "No MXSession.");
        finish();
        return;
    }

    mMyUserId = mSession.getCredentials().userId;

    CommonActivityUtils.resumeEventStream(this);

    mRoom = mSession.getDataHandler().getRoom(roomId);

    FragmentManager fm = getSupportFragmentManager();
    mConsoleMessageListFragment = (ConsoleMessageListFragment) fm
            .findFragmentByTag(TAG_FRAGMENT_MATRIX_MESSAGE_LIST);

    if (mConsoleMessageListFragment == null) {
        // this fragment displays messages and handles all message logic
        mConsoleMessageListFragment = ConsoleMessageListFragment.newInstance(mMyUserId, mRoom.getRoomId(),
                org.matrix.androidsdk.R.layout.fragment_matrix_message_list_fragment);
        fm.beginTransaction().add(R.id.anchor_fragment_messages, mConsoleMessageListFragment,
                TAG_FRAGMENT_MATRIX_MESSAGE_LIST).commit();
    }

    // set general room information
    setTitle(mRoom.getName(mMyUserId));
    setTopic(mRoom.getTopic());

    // listen for room name or topic changes
    mRoom.addEventListener(mEventListener);

    // The error listener needs the current activity
    mSession.setFailureCallback(new ErrorListener(this));

    mImagePreviewLayout = findViewById(R.id.room_image_preview_layout);
    mImagePreviewView = (ImageView) findViewById(R.id.room_image_preview);
    mImagePreviewButton = (ImageButton) findViewById(R.id.room_image_preview_cancel_button);

    // the user cancels the image selection
    mImagePreviewButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mPendingThumbnailUrl = null;
            mPendingMediaUrl = null;
            mPendingMimeType = null;
            mPendingFilename = null;
            manageSendMoreButtons();
        }
    });

    mLatestChatMessageCache = Matrix.getInstance(this).getDefaultLatestChatMessageCache();
    mMediasCache = Matrix.getInstance(this).getMediasCache();

    // some medias must be sent while opening the chat
    if (intent.hasExtra(HomeActivity.EXTRA_ROOM_INTENT)) {
        final Intent mediaIntent = intent.getParcelableExtra(HomeActivity.EXTRA_ROOM_INTENT);

        // sanity check
        if (null != mediaIntent) {
            mEditText.postDelayed(new Runnable() {
                @Override
                public void run() {
                    sendMediasIntent(mediaIntent);
                }
            }, 1000);
        }
    }
}

From source file:org.matrix.console.activity.RoomActivity.java

/**
 * Send a list of images from their URIs
 * @param mediaUris the media URIs/*  w  ww  . j  a  v a 2s .co m*/
 */
private void sendMedias(final ArrayList<Uri> mediaUris) {

    final View progressBackground = findViewById(R.id.medias_processing_progress_background);
    final View progress = findViewById(R.id.medias_processing_progress);

    progressBackground.setVisibility(View.VISIBLE);
    progress.setVisibility(View.VISIBLE);

    final HandlerThread handlerThread = new HandlerThread("MediasEncodingThread");
    handlerThread.start();

    final android.os.Handler handler = new android.os.Handler(handlerThread.getLooper());

    Runnable r = new Runnable() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    final int mediaCount = mediaUris.size();

                    for (Uri anUri : mediaUris) {
                        // crash from Google Analytics : null URI on a nexus 5
                        if (null != anUri) {
                            final Uri mediaUri = anUri;
                            String filename = null;

                            if (mediaUri.toString().startsWith("content://")) {
                                Cursor cursor = null;
                                try {
                                    cursor = RoomActivity.this.getContentResolver().query(mediaUri, null, null,
                                            null, null);
                                    if (cursor != null && cursor.moveToFirst()) {
                                        filename = cursor
                                                .getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                                    }
                                } catch (Exception e) {
                                    Log.e(LOG_TAG, "cursor.getString " + e.getMessage());
                                } finally {
                                    if (null != cursor) {
                                        cursor.close();
                                    }
                                }

                                if (TextUtils.isEmpty(filename)) {
                                    List uriPath = mediaUri.getPathSegments();
                                    filename = (String) uriPath.get(uriPath.size() - 1);
                                }
                            } else if (mediaUri.toString().startsWith("file://")) {
                                // try to retrieve the filename from the file url.
                                try {
                                    filename = anUri.getLastPathSegment();
                                } catch (Exception e) {
                                }

                                if (TextUtils.isEmpty(filename)) {
                                    filename = null;
                                }
                            }

                            final String fFilename = filename;

                            ResourceUtils.Resource resource = ResourceUtils.openResource(RoomActivity.this,
                                    mediaUri);

                            if (null == resource) {
                                RoomActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        handlerThread.quit();
                                        progressBackground.setVisibility(View.GONE);
                                        progress.setVisibility(View.GONE);

                                        Toast.makeText(RoomActivity.this,
                                                getString(R.string.message_failed_to_upload), Toast.LENGTH_LONG)
                                                .show();
                                    }

                                    ;
                                });

                                return;
                            }

                            // save the file in the filesystem
                            String mediaUrl = mMediasCache.saveMedia(resource.contentStream, null,
                                    resource.mimeType);
                            String mimeType = resource.mimeType;
                            Boolean isManaged = false;

                            if ((null != resource.mimeType) && resource.mimeType.startsWith("image/")) {
                                // manage except if there is an error
                                isManaged = true;

                                // try to retrieve the gallery thumbnail
                                // if the image comes from the gallery..
                                Bitmap thumbnailBitmap = null;

                                try {
                                    ContentResolver resolver = getContentResolver();

                                    List uriPath = mediaUri.getPathSegments();
                                    long imageId = -1;
                                    String lastSegment = (String) uriPath.get(uriPath.size() - 1);

                                    // > Kitkat
                                    if (lastSegment.startsWith("image:")) {
                                        lastSegment = lastSegment.substring("image:".length());
                                    }

                                    imageId = Long.parseLong(lastSegment);

                                    thumbnailBitmap = MediaStore.Images.Thumbnails.getThumbnail(resolver,
                                            imageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
                                } catch (Exception e) {
                                    Log.e(LOG_TAG,
                                            "MediaStore.Images.Thumbnails.getThumbnail " + e.getMessage());
                                }

                                double thumbnailWidth = mConsoleMessageListFragment.getMaxThumbnailWith();
                                double thumbnailHeight = mConsoleMessageListFragment.getMaxThumbnailHeight();

                                // no thumbnail has been found or the mimetype is unknown
                                if ((null == thumbnailBitmap) || (thumbnailBitmap.getHeight() > thumbnailHeight)
                                        || (thumbnailBitmap.getWidth() > thumbnailWidth)) {
                                    // need to decompress the high res image
                                    BitmapFactory.Options options = new BitmapFactory.Options();
                                    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                                    resource = ResourceUtils.openResource(RoomActivity.this, mediaUri);

                                    // get the full size bitmap
                                    Bitmap fullSizeBitmap = null;

                                    if (null == thumbnailBitmap) {
                                        fullSizeBitmap = BitmapFactory.decodeStream(resource.contentStream,
                                                null, options);
                                    }

                                    if ((fullSizeBitmap != null) || (thumbnailBitmap != null)) {
                                        double imageWidth;
                                        double imageHeight;

                                        if (null == thumbnailBitmap) {
                                            imageWidth = fullSizeBitmap.getWidth();
                                            imageHeight = fullSizeBitmap.getHeight();
                                        } else {
                                            imageWidth = thumbnailBitmap.getWidth();
                                            imageHeight = thumbnailBitmap.getHeight();
                                        }

                                        if (imageWidth > imageHeight) {
                                            thumbnailHeight = thumbnailWidth * imageHeight / imageWidth;
                                        } else {
                                            thumbnailWidth = thumbnailHeight * imageWidth / imageHeight;
                                        }

                                        try {
                                            thumbnailBitmap = Bitmap.createScaledBitmap(
                                                    (null == fullSizeBitmap) ? thumbnailBitmap : fullSizeBitmap,
                                                    (int) thumbnailWidth, (int) thumbnailHeight, false);
                                        } catch (OutOfMemoryError ex) {
                                            Log.e(LOG_TAG, "Bitmap.createScaledBitmap " + ex.getMessage());
                                        }
                                    }

                                    // the valid mimetype is not provided
                                    if ("image/*".equals(mimeType)) {
                                        // make a jpg snapshot.
                                        mimeType = null;
                                    }

                                    // unknown mimetype
                                    if ((null == mimeType) || (mimeType.startsWith("image/"))) {
                                        try {
                                            // try again
                                            if (null == fullSizeBitmap) {
                                                System.gc();
                                                fullSizeBitmap = BitmapFactory
                                                        .decodeStream(resource.contentStream, null, options);
                                            }

                                            if (null != fullSizeBitmap) {
                                                Uri uri = Uri.parse(mediaUrl);

                                                if (null == mimeType) {
                                                    // the images are save in jpeg format
                                                    mimeType = "image/jpeg";
                                                }

                                                resource.contentStream.close();
                                                resource = ResourceUtils.openResource(RoomActivity.this,
                                                        mediaUri);

                                                try {
                                                    mMediasCache.saveMedia(resource.contentStream,
                                                            uri.getPath(), mimeType);
                                                } catch (OutOfMemoryError ex) {
                                                    Log.e(LOG_TAG, "mMediasCache.saveMedia" + ex.getMessage());
                                                }

                                            } else {
                                                isManaged = false;
                                            }

                                            resource.contentStream.close();

                                        } catch (Exception e) {
                                            isManaged = false;
                                            Log.e(LOG_TAG, "sendMedias " + e.getMessage());
                                        }
                                    }

                                    // reduce the memory consumption
                                    if (null != fullSizeBitmap) {
                                        fullSizeBitmap.recycle();
                                        System.gc();
                                    }
                                }

                                String thumbnailURL = mMediasCache.saveBitmap(thumbnailBitmap, null);

                                if (null != thumbnailBitmap) {
                                    thumbnailBitmap.recycle();
                                }

                                //
                                if (("image/jpg".equals(mimeType) || "image/jpeg".equals(mimeType))
                                        && (null != mediaUrl)) {

                                    Uri imageUri = Uri.parse(mediaUrl);
                                    // get the exif rotation angle
                                    final int rotationAngle = ImageUtils
                                            .getRotationAngleForBitmap(RoomActivity.this, imageUri);

                                    if (0 != rotationAngle) {
                                        // always apply the rotation to the image
                                        ImageUtils.rotateImage(RoomActivity.this, thumbnailURL, rotationAngle,
                                                mMediasCache);

                                        // the high res media orientation should be not be done on uploading
                                        //ImageUtils.rotateImage(RoomActivity.this, mediaUrl, rotationAngle, mMediasCache))
                                    }
                                }

                                // is the image content valid ?
                                if (isManaged && (null != thumbnailURL)) {

                                    final String fThumbnailURL = thumbnailURL;
                                    final String fMediaUrl = mediaUrl;
                                    final String fMimeType = mimeType;

                                    RoomActivity.this.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            // if there is only one image
                                            if (mediaCount == 1) {
                                                // display an image preview before sending it
                                                mPendingThumbnailUrl = fThumbnailURL;
                                                mPendingMediaUrl = fMediaUrl;
                                                mPendingMimeType = fMimeType;
                                                mPendingFilename = fFilename;

                                                mConsoleMessageListFragment.scrollToBottom();

                                                manageSendMoreButtons();
                                            } else {
                                                mConsoleMessageListFragment.uploadImageContent(fThumbnailURL,
                                                        fMediaUrl, fFilename, fMimeType);
                                            }
                                        }
                                    });
                                }
                            }

                            // default behaviour
                            if ((!isManaged) && (null != mediaUrl)) {
                                final String fMediaUrl = mediaUrl;
                                final String fMimeType = mimeType;

                                RoomActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if ((null != fMimeType) && fMimeType.startsWith("video/")) {
                                            mConsoleMessageListFragment.uploadVideoContent(fMediaUrl, null,
                                                    fMimeType);
                                        } else {
                                            mConsoleMessageListFragment.uploadFileContent(fMediaUrl, fMimeType,
                                                    fFilename);
                                        }
                                    }
                                });
                            }
                        }
                    }

                    RoomActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            handlerThread.quit();
                            progressBackground.setVisibility(View.GONE);
                            progress.setVisibility(View.GONE);
                        };
                    });
                }
            });
        }
    };

    Thread t = new Thread(r);
    t.start();
}