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:im.vector.util.VectorRoomMediasSender.java

/**
 * Offer to resize the image before sending it.
 * @param aThumbnailURL the thumbnail url
 * @param anImageUrl the image url./*from   w ww  .  jav  a2s .c  om*/
 * @param anImageFilename the image filename
 * @param anImageMimeType the image mimetype
 * @param aListener the listener
 */
private void sendImageMessage(final String aThumbnailURL, final String anImageUrl, final String anImageFilename,
        final String anImageMimeType, final OnImageUploadListener aListener) {
    // sanity check
    if ((null == anImageUrl) || (null == aListener)) {
        return;
    }

    boolean isManaged = false;

    // check if the media could be resized
    if ((null != aThumbnailURL) && (CommonActivityUtils.MIME_TYPE_JPEG.equals(anImageMimeType)
            || CommonActivityUtils.MIME_TYPE_JPG.equals(anImageMimeType)
            || CommonActivityUtils.MIME_TYPE_IMAGE_ALL.equals(anImageMimeType))) {
        System.gc();
        FileInputStream imageStream;

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

            final int rotationAngle = ImageUtils.getRotationAngleForBitmap(mVectorRoomActivity, 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;

            // retrieve the image size
            try {
                BitmapFactory.decodeStream(imageStream, null, options);
            } catch (OutOfMemoryError e) {
                Log.e(LOG_TAG, "sendImageMessage out of memory error : " + e.getMessage());
            }

            final ImageCompressionSizes imageSizes = computeImageSizes(options.outWidth, options.outHeight);

            imageStream.close();

            // the user already selects a compression
            if (null != mImageCompressionDescription) {
                isManaged = true;

                final ImageSize expectedSize = imageSizes.getImageSize(mVectorRoomActivity,
                        mImageCompressionDescription);
                final String fImageUrl = resizeImage(anImageUrl, filename, imageSizes.mFullImageSize,
                        expectedSize, rotationAngle);

                mVectorRoomActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mVectorMessageListFragment.uploadImageContent(aThumbnailURL, fImageUrl, anImageFilename,
                                anImageMimeType);
                        aListener.onDone();
                    }
                });
            }
            // can be rescaled ?
            else if (null != imageSizes.mSmallImageSize) {
                isManaged = true;

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

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

                String[] stringsArray = getImagesCompressionTextsList(mVectorRoomActivity, imageSizes,
                        fileSize);

                final AlertDialog.Builder alert = new AlertDialog.Builder(mVectorRoomActivity);
                alert.setTitle(mVectorRoomActivity.getString(im.vector.R.string.compression_options));
                alert.setSingleChoiceItems(stringsArray, -1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        final int fPos = which;

                        mImageSizesListDialog.dismiss();

                        mVectorRoomActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mVectorRoomActivity.setProgressVisibility(View.VISIBLE);

                                Thread thread = new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ImageSize expectedSize = null;

                                        // full size
                                        if (0 != fPos) {
                                            expectedSize = imageSizes.getImageSizesList().get(fPos);
                                        }

                                        // stored the compression selected by the user
                                        mImageCompressionDescription = imageSizes
                                                .getImageSizesDescription(mVectorRoomActivity).get(fPos);

                                        final String fImageUrl = resizeImage(anImageUrl, filename,
                                                imageSizes.mFullImageSize, expectedSize, rotationAngle);

                                        mVectorRoomActivity.runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                mVectorMessageListFragment.uploadImageContent(aThumbnailURL,
                                                        fImageUrl, anImageFilename, anImageMimeType);
                                                aListener.onDone();
                                            }
                                        });
                                    }
                                });

                                thread.setPriority(Thread.MIN_PRIORITY);
                                thread.start();
                            }
                        });
                    }
                });

                mImageSizesListDialog = alert.show();
                mImageSizesListDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        mImageSizesListDialog = null;
                        if (null != aListener) {
                            aListener.onCancel();
                        }
                    }
                });
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "sendImageMessage failed " + e.getMessage());
        }
    }

    // cannot resize, let assumes that it has been done
    if (!isManaged) {
        mVectorRoomActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mVectorMessageListFragment.uploadImageContent(aThumbnailURL, anImageUrl, anImageFilename,
                        anImageMimeType);
                if (null != aListener) {
                    aListener.onDone();
                }
            }
        });
    }
}

From source file:im.neon.util.VectorRoomMediasSender.java

/**
 * Offer to resize the image before sending it.
 * @param aThumbnailURL the thumbnail url
 * @param anImageUrl the image url.// w w w .  ja  v a2 s  . c o  m
 * @param anImageFilename the image filename
 * @param anImageMimeType the image mimetype
 * @param aListener the listener
 */
private void sendImageMessage(final String aThumbnailURL, final String anImageUrl, final String anImageFilename,
        final String anImageMimeType, final OnImageUploadListener aListener) {
    // sanity check
    if ((null == anImageUrl) || (null == aListener)) {
        return;
    }

    boolean isManaged = false;

    // check if the media could be resized
    if ((null != aThumbnailURL) && (CommonActivityUtils.MIME_TYPE_JPEG.equals(anImageMimeType)
            || CommonActivityUtils.MIME_TYPE_JPG.equals(anImageMimeType)
            || CommonActivityUtils.MIME_TYPE_IMAGE_ALL.equals(anImageMimeType))) {
        System.gc();
        FileInputStream imageStream;

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

            final int rotationAngle = ImageUtils.getRotationAngleForBitmap(mVectorRoomActivity, 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;

            // retrieve the image size
            try {
                BitmapFactory.decodeStream(imageStream, null, options);
            } catch (OutOfMemoryError e) {
                Log.e(LOG_TAG, "sendImageMessage out of memory error : " + e.getMessage());
            }

            final ImageCompressionSizes imageSizes = computeImageSizes(options.outWidth, options.outHeight);

            imageStream.close();

            // the user already selects a compression
            if (null != mImageCompressionDescription) {
                isManaged = true;

                final ImageSize expectedSize = imageSizes.getImageSize(mVectorRoomActivity,
                        mImageCompressionDescription);
                final String fImageUrl = resizeImage(anImageUrl, filename, imageSizes.mFullImageSize,
                        expectedSize, rotationAngle);

                mVectorRoomActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mVectorMessageListFragment.uploadImageContent(null, null, aThumbnailURL, fImageUrl,
                                anImageFilename, anImageMimeType);
                        aListener.onDone();
                    }
                });
            }
            // can be rescaled ?
            else if (null != imageSizes.mSmallImageSize) {
                isManaged = true;

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

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

                String[] stringsArray = getImagesCompressionTextsList(mVectorRoomActivity, imageSizes,
                        fileSize);

                final AlertDialog.Builder alert = new AlertDialog.Builder(mVectorRoomActivity);
                alert.setTitle(mVectorRoomActivity.getString(im.neon.R.string.compression_options));
                alert.setSingleChoiceItems(stringsArray, -1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        final int fPos = which;

                        mImageSizesListDialog.dismiss();

                        mVectorRoomActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mVectorRoomActivity.setProgressVisibility(View.VISIBLE);

                                Thread thread = new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ImageSize expectedSize = null;

                                        // full size
                                        if (0 != fPos) {
                                            expectedSize = imageSizes.getImageSizesList().get(fPos);
                                        }

                                        // stored the compression selected by the user
                                        mImageCompressionDescription = imageSizes
                                                .getImageSizesDescription(mVectorRoomActivity).get(fPos);

                                        final String fImageUrl = resizeImage(anImageUrl, filename,
                                                imageSizes.mFullImageSize, expectedSize, rotationAngle);

                                        mVectorRoomActivity.runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                mVectorMessageListFragment.uploadImageContent(null, null,
                                                        aThumbnailURL, fImageUrl, anImageFilename,
                                                        anImageMimeType);
                                                aListener.onDone();
                                            }
                                        });
                                    }
                                });

                                thread.setPriority(Thread.MIN_PRIORITY);
                                thread.start();
                            }
                        });
                    }
                });

                mImageSizesListDialog = alert.show();
                mImageSizesListDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        mImageSizesListDialog = null;
                        if (null != aListener) {
                            aListener.onCancel();
                        }
                    }
                });
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "sendImageMessage failed " + e.getMessage());
        }
    }

    // cannot resize, let assumes that it has been done
    if (!isManaged) {
        mVectorRoomActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mVectorMessageListFragment.uploadImageContent(null, null, aThumbnailURL, anImageUrl,
                        anImageFilename, anImageMimeType);
                if (null != aListener) {
                    aListener.onDone();
                }
            }
        });
    }
}

From source file:org.ttrssreader.net.JSONConnector.java

/**
 * parse articles from JSON-reader/*from ww  w. j a v a  2s. co m*/
 *
 * @param articles  container, where parsed articles will be stored
 * @param reader    JSON-reader, containing articles (received from server)
 * @param skipNames set of names (article properties), which should not be processed (may be {@code null})
 * @param filter    filter for articles, defining which articles should be omitted while parsing (may be {@code
 *                  null})
 * @return amount of processed articles
 */
private int parseArticleArray(final Set<Article> articles, JsonReader reader,
        Set<Article.ArticleField> skipNames, IArticleOmitter filter) {
    long time = System.currentTimeMillis();
    int count = 0;

    try {
        reader.beginArray();
        while (reader.hasNext()) {
            Article article = new Article();

            reader.beginObject();
            boolean skipObject = parseArticle(article, reader, skipNames, filter);
            reader.endObject();

            if (!skipObject && article.id != -1 && article.title != null)
                articles.add(article);

            count++;
        }
        reader.endArray();
    } catch (OutOfMemoryError e) {
        Controller.getInstance().lowMemory(true); // Low memory detected
    } catch (Exception e) {
        Log.e(TAG, "Input data could not be read: " + e.getMessage() + " (" + e.getCause() + ")", e);
    }

    Log.d(TAG, String.format("parseArticleArray: parsing %s articles took %s ms", count,
            (System.currentTimeMillis() - time)));
    return count;
}

From source file:net.sf.ehcache.store.DiskStore.java

private void writeElement(Element element, Serializable key) throws IOException {
    try {/*  w w w  .ja va  2  s . c  o  m*/
        int bufferLength;
        long expirationTime = element.getExpirationTime();

        try {
            MemoryEfficientByteArrayOutputStream buffer = MemoryEfficientByteArrayOutputStream
                    .serialize(element, estimatedPayloadSize());

            bufferLength = buffer.size();
            DiskElement diskElement = checkForFreeBlock(bufferLength);

            // Write the record
            randomAccessFile.seek(diskElement.position);
            randomAccessFile.write(buffer.toByteArray(), 0, bufferLength);
            buffer = null;

            // Add to index, update stats
            diskElement.payloadSize = bufferLength;
            diskElement.key = key;
            diskElement.expiryTime = expirationTime;
            diskElement.hitcount = element.getHitCount();
            totalSize += bufferLength;
            lastElementSize = bufferLength;
            synchronized (diskElements) {
                diskElements.put(key, diskElement);
            }
        } catch (OutOfMemoryError e) {
            LOG.error("OutOfMemoryError on serialize: " + key);

        }

    } catch (Exception e) {
        // Catch any exception that occurs during serialization
        LOG.error(name + "Cache: Failed to write element to disk '" + key + "'. Initial cause was "
                + e.getMessage(), e);
    }

}

From source file:com.google.acre.script.HostEnv.java

public void bootScript() {

    req.server_host = ACRE_HOST_DELIMITER_PATH + "." + ACRE_HOST_BASE;
    req.server_host_base = ACRE_HOST_BASE;
    req.freebase_service_url = "http://" + ACRE_METAWEB_API_ADDR;
    if (ACRE_METAWEB_API_ADDR_PORT != 80)
        req.freebase_service_url += ":" + ACRE_METAWEB_API_ADDR_PORT;
    req.freebase_site_host = "http://" + ACRE_FREEBASE_SITE_ADDR;
    if (ACRE_FREEBASE_SITE_ADDR_PORT != 80)
        req.freebase_site_host += ":" + ACRE_FREEBASE_SITE_ADDR_PORT;
    req.site_host = "http://" + ACRE_SITE_HOST;
    if (ACRE_SITE_HOST_PORT != 80)
        req.site_host += ":" + ACRE_SITE_HOST;
    req.googleapis_host = ACRE_GOOGLEAPIS_HOST;
    req.googleapis_key = ACRE_GOOGLEAPIS_KEY;
    req.googleapis_rpc = ACRE_GOOGLEAPIS_RPC;
    req.googleapis_freebase_version = ACRE_GOOGLEAPIS_FREEBASE_VERSION;

    _scope.put("PROTECTED_HOSTENV", _scope, this);

    this.put("ACRE_HOST_BASE", this, Configuration.Values.ACRE_HOST_BASE.getValue());
    this.put("ACRE_HOST_DELIMITER_HOST", this, Configuration.Values.ACRE_HOST_DELIMITER_HOST.getValue());
    this.put("ACRE_HOST_DELIMITER_PATH", this, Configuration.Values.ACRE_HOST_DELIMITER_PATH.getValue());
    this.put("STATIC_SCRIPT_PATH", this, Configuration.Values.STATIC_SCRIPT_PATH.getValue());
    this.put("ACRE_DEVELOPER_MODE", this, ACRE_DEVELOPER_MODE);
    this.put("ACRE_REMOTE_REQUIRE", this, ACRE_REMOTE_REQUIRE);
    this.put("DEFAULT_HOST_PATH", this, DEFAULT_HOST_PATH);

    _scope.put("ACRE_REQUEST", _scope, req.toJsObject(_scope));

    try {//  w  w w.j  ava  2 s.  c om
        syslog(INFO, "hostenv.script.start", "");

        // we ought to make sure acreboot has initialized before
        // throwing this error
        if (LIMIT_EXECUTION_TIME && System.currentTimeMillis() > req._deadline) {
            throw new AcreDeadlineError("Request chain time quota expired");
        }

        if (_scope.has("acre", _scope)) {
            throw new RuntimeException("FATAL: bootScript() re-entered with same scope");
        }

        try {
            load_system_script("acreboot.js", _scope);
        } catch (JavaScriptException jsexc) {
            Object exit_exception_obj = this.get("AcreExitException", this);
            if (exit_exception_obj instanceof Scriptable) {
                Object val = jsexc.getValue();
                Scriptable exit_exception = (Scriptable) exit_exception_obj;
                if ((val instanceof Scriptable && !exit_exception.hasInstance((Scriptable) val))
                        || !(val instanceof Scriptable)) {
                    renderErrorPage("JS exception", jsexc, "hostenv.script.error.jsexception");
                    return;
                } else if (val instanceof Scriptable && exit_exception.hasInstance((Scriptable) val)) {
                    Object spath = ((Scriptable) val).get("route_to", (Scriptable) val);
                    Object skip_routes = ((Scriptable) val).get("skip_routes", (Scriptable) val);

                    if (spath instanceof String) {
                        internalRedirect((String) spath, (Boolean) skip_routes);
                        return;
                    }
                }
            } else {
                throw jsexc;
            }
        }

        try {
            Object finisher = this.get("finish_response", this);
            if (finisher != null) {
                Object[] args = {};
                // throw away result
                ((Callable) finisher).call(_context, _scope, _scope, args);
            }
        } catch (JavaScriptException jsexc) {
            // not even AcreExitException is ok here.
            renderErrorPage("JS exception closing response", jsexc, "hostenv.script.error.jsexception");
            return;
        }

        closeResponse();

    } catch (RhinoException rexc) {
        renderErrorPage("Unhandled exception", rexc, "hostenv.script.error.jsexception");
    } catch (AcreScriptError ase) {
        renderErrorPage("Unrecoverable error: " + ase.getMessage(), ase,
                "hostenv.script.error.acrescripterror");
    } catch (StackOverflowError soe) {
        renderErrorPage("Stack overflow", soe, "hostenv.script.error.stackoverflowerror");
    } catch (OutOfMemoryError oome) {
        if (oome.getMessage().matches("PermGen space")) {
            reportDisaster("Unhandlable java OutOfMemoryError", oome);
            System.exit(1);
        }
        // record the fact that we have exceeded the memory quota in the regular call
        // this is done because the error page will reset the memory quota and lose
        // this information. This is needed to record the real amount of memory used.
        res._used_memory = allocationLimit;
        renderErrorPage("Memory limit exceeded", oome, "hostenv.script.error.outofmemoryerror");
    } catch (AcreThreadDeath td) {
        renderErrorPage("Execution time limit exceeded", td, "hostenv.script.error.threaddeath");
    } catch (AcreDeadlineError td) {
        renderErrorPage("Execution time limit exceeded", td, "hostenv.script.error.deadline");
    } catch (IOException ioe) {
        reportDisaster("I/O exception reached toplevel", ioe);
        if (ioe.getMessage().matches("Too many open files")) {
            System.exit(1);
        }
    } catch (Throwable t) {
        reportDisaster("Fatal exception reached toplevel", t);
    } finally {
        _async_fetch = null;
        // clean up after running a user script.
    }

}

From source file:com.intel.xdk.device.Device.java

public void getRemoteDataExt(JSONObject obj) {
    String requestUrl;/*w w w  .  ja v a 2  s .  c  o  m*/
    String id;
    String method;
    String body;
    String headers;
    try {
        //Request url
        requestUrl = obj.getString("url");

        //ID that correlates the request to the event
        id = obj.getString("id");

        //Request method
        method = obj.getString("method");

        //Request body
        body = obj.getString("body");

        //Request header
        headers = obj.getString("headers");

        String js = null;
        if (method == null || method.length() == 0)
            method = "GET";

        HttpURLConnection connection = (HttpURLConnection) new URL(requestUrl).openConnection();
        boolean forceUTF8 = false;

        try {
            if (headers.length() > 0) {
                String[] headerArray = headers.split("&");

                //Set request header
                for (String header : headerArray) {
                    String[] headerPair = header.split("=");
                    if (headerPair.length == 2) {
                        String field = headerPair[0];
                        String value = headerPair[1];
                        if (field != null && value != null) {
                            if (!"content-length".equals(field.toLowerCase())) {//skip Content-Length - causes error because it is managed by the request
                                connection.setRequestProperty(field, value);
                            }

                            field = field.toLowerCase();
                            value = value.toLowerCase();
                            if (field.equals("content-type") && value.indexOf("charset") > -1
                                    && value.indexOf("utf-8") > -1) {
                                forceUTF8 = true;
                            }
                        }
                    }
                }

            }

            if ("POST".equalsIgnoreCase(method)) {
                connection.setRequestMethod(method);
                connection.setDoOutput(true);
                connection.setFixedLengthStreamingMode(body.length());
                DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
                dStream.writeBytes(body);
                dStream.flush();
                dStream.close();
            }

            //inject response
            int statusCode = connection.getResponseCode();

            final StringBuilder response = new StringBuilder();
            try {
                InputStream responseStream = connection.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(responseStream));
                String line;
                while ((line = br.readLine()) != null) {
                    response.append(line);
                }
                br.close();
            } catch (Exception e) {
            }

            String responseBody = null;
            // how to handle UTF8 without EntityUtils?
            //                if (forceUTF8) {
            //                    responseBody = EntityUtils.toString(entity, "UTF-8");
            //                } else {
            //                    responseBody = EntityUtils.toString(entity);
            //                }
            responseBody = response.toString();
            String responseMessage = connection.getResponseMessage();

            char[] bom = { 0xef, 0xbb, 0xbf };
            //check for BOM characters, then strip if present
            if (responseBody.length() >= 3 && responseBody.charAt(0) == bom[0]
                    && responseBody.charAt(1) == bom[1] && responseBody.charAt(2) == bom[2]) {
                responseBody = responseBody.substring(3);
            }

            //escape existing backslashes
            responseBody = responseBody.replaceAll("\\\\", "\\\\\\\\");

            //escape internal double-quotes
            responseBody = responseBody.replaceAll("\"", "\\\\\"");
            responseBody = responseBody.replaceAll("'", "\\\\'");

            //replace linebreaks with \n
            responseBody = responseBody.replaceAll("\\r\\n|\\r|\\n", "\\\\n");

            StringBuilder extras = new StringBuilder("{");
            extras.append(String.format("status:'%d',", statusCode));

            String status = null;
            switch (statusCode) {
            case 200:
                status = "OK";
                break;
            case 201:
                status = "CREATED";
                break;
            case 202:
                status = "Accepted";
                break;
            case 203:
                status = "Partial Information";
                break;
            case 204:
                status = "No Response";
                break;
            case 301:
                status = "Moved";
                break;
            case 302:
                status = "Found";
                break;
            case 303:
                status = "Method";
                break;
            case 304:
                status = "Not Modified";
                break;
            case 400:
                status = "Bad request";
                break;
            case 401:
                status = "Unauthorized";
                break;
            case 402:
                status = "PaymentRequired";
                break;
            case 403:
                status = "Forbidden";
                break;
            case 404:
                status = "Not found";
                break;
            case 500:
                status = "Internal Error";
                break;
            case 501:
                status = "Not implemented";
                break;
            case 502:
                status = "Service temporarily overloaded";
                break;
            case 503:
                status = "Gateway timeout";
                break;
            }
            extras.append(String.format("statusText:'%s',", status));
            extras.append("headers: {");

            List<String> cookieData = new ArrayList<String>();
            Map<String, List<String>> allHeaders = connection.getHeaderFields();
            for (String key : allHeaders.keySet()) {
                if (key == null) {
                    continue;
                }
                String value = connection.getHeaderField(key);
                value = value.replaceAll("'", "\\\\'");
                if (key.toLowerCase().equals("set-cookie"))
                    cookieData.add(value);
                else
                    extras.append(String.format("'%s':'%s',", key, value));
            }

            String concatCookies = cookieData.toString();
            concatCookies = concatCookies.substring(0, concatCookies.length());
            extras.append(String.format("'Set-Cookie':'%s',",
                    concatCookies.substring(1, concatCookies.length() - 1)));

            String cookieArray = "[";
            for (int i = 0; i < cookieData.size(); i++)
                cookieArray += String.format("'%s',", cookieData.get(i));
            cookieArray += "]";

            extras.append("'All-Cookies': " + cookieArray);
            extras.append("} }");

            js = String.format(
                    "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.remote.data',true,true);e.success=true;e.id='%s';e.response='%s';e.extras=%s;document.dispatchEvent(e);",
                    id, responseBody, extras.toString());

        } catch (Exception ex) {
            js = String.format(
                    "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.remote.data',true,true);e.success=false;e.id='%s';e.response='';e.extras={};e.error='%s';document.dispatchEvent(e);",
                    id, ex.getMessage());
        } catch (OutOfMemoryError err) {
            js = String.format(
                    "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.remote.data',true,true);e.success=false;e.id='%s';e.response='';e.extras={};e.error='%s';document.dispatchEvent(e);",
                    id, err.getMessage());
        } finally {
            connection.disconnect();
        }

        injectJS(js);

    } catch (Exception e) {
        Log.d("getRemoteDataExt", e.getMessage());
    }
}

From source file:ru.valle.btc.MainActivity.java

private void encryptOrDecryptPrivateKey() {
    final KeyPair inputKeyPair = currentKeyPair;
    final String password = getString(passwordEdit);
    if (inputKeyPair != null && !TextUtils.isEmpty(password)) {
        cancelAllRunningTasks();/*from  w w  w.j av  a2  s  . co m*/
        final boolean decrypting = inputKeyPair.privateKey.type == BTCUtils.Bip38PrivateKeyInfo.TYPE_BIP38
                && inputKeyPair.privateKey.privateKeyDecoded == null;
        lastBip38ActionWasDecryption = decrypting;
        passwordButton.setEnabled(false);
        passwordButton.setText(decrypting ? R.string.decrypting : R.string.encrypting);
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(
                Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(passwordEdit.getWindowToken(), 0);

        bip38Task = new AsyncTask<Void, Void, Object>() {
            ProgressDialog dialog;
            public boolean sendLayoutVisible;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(MainActivity.this, "",
                        (decrypting ? getString(R.string.decrypting) : getString(R.string.encrypting)), true);
                dialog.setCancelable(true);
                dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        bip38Task.cancel(true);
                        bip38Task = null;
                    }
                });
                sendLayoutVisible = sendLayout.isShown();
            }

            @Override
            protected Object doInBackground(Void... params) {
                try {
                    if (decrypting) {
                        return BTCUtils.bip38Decrypt(inputKeyPair.privateKey.privateKeyEncoded, password);
                    } else {
                        String encryptedPrivateKey = BTCUtils.bip38Encrypt(inputKeyPair, password);
                        return new KeyPair(new BTCUtils.Bip38PrivateKeyInfo(encryptedPrivateKey,
                                inputKeyPair.privateKey.privateKeyDecoded, password,
                                inputKeyPair.privateKey.isPublicKeyCompressed));
                    }
                } catch (OutOfMemoryError e) {
                    return R.string.error_oom_bip38;
                } catch (Throwable e) {
                    String msg = e.getMessage();
                    if (msg != null && msg.contains("OutOfMemoryError")) {
                        return R.string.error_oom_bip38;
                    } else {
                        return null;
                    }
                }
            }

            @Override
            protected void onPostExecute(Object result) {
                bip38Task = null;
                dialog.dismiss();
                if (result instanceof KeyPair) {
                    KeyPair keyPair = (KeyPair) result;
                    insertingPrivateKeyProgrammatically = true;
                    privateKeyTextEdit.setText(keyPair.privateKey.privateKeyEncoded);
                    insertingPrivateKeyProgrammatically = false;
                    onKeyPairModify(false, keyPair);
                    if (!decrypting) {
                        sendLayout.setVisibility(sendLayoutVisible ? View.VISIBLE : View.GONE);
                    }
                } else if (result instanceof Integer || !decrypting) {
                    onKeyPairModify(false, inputKeyPair);
                    new AlertDialog.Builder(MainActivity.this)
                            .setMessage(getString(
                                    result instanceof Integer ? (Integer) result : R.string.error_unknown))
                            .setPositiveButton(android.R.string.ok, null).show();
                } else {
                    onKeyPairModify(false, inputKeyPair);
                    ((TextView) findViewById(R.id.err_password)).setText(R.string.incorrect_password);
                }
            }

            @Override
            protected void onCancelled() {
                super.onCancelled();
                bip38Task = null;
                dialog.dismiss();
                onKeyPairModify(false, currentKeyPair);
            }
        }.execute();
    }
}

From source file:edu.harvard.i2b2.adminTool.dataModel.PatientMappingFactory.java

public String createlld(int minPatientNum, int maxPatientNum, boolean bDisplayAll, boolean writeFile,
        boolean displayDemographics) {

    ArrayList conceptOrder = new ArrayList();
    int maxLineCount = 0; // zero turns off check for maximum count of lines
    StringBuilder resultFile = new StringBuilder();
    ArrayList<PatientDemographics> demographicsArray = new ArrayList<PatientDemographics>();

    try {//w  w w.  ja  v  a  2 s  .  co m
        // get the root
        Element root = null;// doc.getRootElement();
        // get the children from the i2b2 document
        java.util.List allChildren = root.getChildren();
        int iNumberOfChildren = allChildren.size();
        // set up the variables for the loop
        String sPatient_num = null;
        String sConcept_cd = null;
        String sOldPatient_num = "start";
        String sOldConcept_cd = null;
        String sStart_date = null;
        String sOldStart_date = null;
        String sEnd_date = null;
        String sInout_cd = null;
        String sDeath_date = null;
        String sColor = null;
        String sHeight = null;
        String sValue = null;
        String sTablename = null;
        int patientNum = 0;
        Date oDate;

        resultFile.append(GetTimelineHeader());
        boolean bOverMax = false;
        int conceptCount = 0;
        int patientCount = minPatientNum;
        StringBuilder patientRecord = new StringBuilder();

        String currentPatientNum = null;
        int indexPos = 0;

        for (int p = 0; p < demographicsArray.size(); p++) {
            PatientDemographics record = demographicsArray.get(p);
            currentPatientNum = record.patientNumber();

            if (displayDemographics) {
                patientRecord.append(getTimelinePatientString(currentPatientNum, record));
            } else {
                patientRecord.append(getTimelinePatientString(currentPatientNum));
            }

            resultFile.append(patientRecord.toString());
            patientRecord = new StringBuilder();
            patientCount++;

            conceptCount = 0;
            sOldConcept_cd = null;
            sOldStart_date = null;
            sOldPatient_num = "";

            if ((indexPos == iNumberOfChildren) && bDisplayAll) {
                conceptCount = 0;
                while ((conceptOrder != null) && (conceptCount < conceptOrder.size())) {
                    patientRecord.append(getTimelineConceptString((String) conceptOrder.get(conceptCount), 1));
                    patientRecord.append(getTimelineEmptyDateString());
                    conceptCount++;
                }

                resultFile.append(patientRecord.toString());
                patientRecord = new StringBuilder();
            }

            for (int i = indexPos; i < iNumberOfChildren; i++) {
                if ((maxLineCount > 0) && (i > maxLineCount)) {
                    bOverMax = true;
                    break;
                }

                Element oChild = (Element) allChildren.get(i);
                sPatient_num = "";// oChild.getChild(ss_patient_num).getText(
                // );

                if (!sPatient_num.equals(currentPatientNum) && (sOldPatient_num.equals("start")) /*
                                                                                                 * &&
                                                                                                 * !sOldPatient_num
                                                                                                 * .equals(
                                                                                                 * sPatient_num
                                                                                                 * )
                                                                                                 */) {
                    if (bDisplayAll) {
                        try {
                            patientNum = Integer.parseInt(sPatient_num);
                            conceptCount = 0;
                            while ((conceptOrder != null) && (conceptCount < conceptOrder.size())) {
                                patientRecord.append(
                                        getTimelineConceptString((String) conceptOrder.get(conceptCount), 1));
                                patientRecord.append(getTimelineEmptyDateString());
                                conceptCount++;
                            }

                            resultFile.append(patientRecord.toString());
                            patientRecord = new StringBuilder();
                            // patientCount++;
                        } catch (java.lang.OutOfMemoryError e) {
                            log.error("In resultset builder 5: " + e.getMessage());
                            // closeConnection(oConnection);
                            return "memory error";
                        } catch (Exception e) {
                            log.error(e.getMessage());
                            // closeConnection(oConnection);
                            return "error";
                        }

                        conceptCount = 0;
                        sOldConcept_cd = null;
                        sOldStart_date = null;
                    }
                    break;
                } else if (!sPatient_num.equals(currentPatientNum) && !(sOldPatient_num.equals("start")) /*
                                                                                                         * &&!
                                                                                                         * sOldPatient_num
                                                                                                         * .equals(
                                                                                                         * sPatient_num
                                                                                                         * )
                                                                                                         */) {
                    if ((bDisplayAll) && (conceptCount < (conceptOrder.size()))) {
                        while ((conceptOrder != null) && (conceptCount < conceptOrder.size())) {
                            patientRecord.append(
                                    getTimelineConceptString((String) conceptOrder.get(conceptCount), 1));
                            patientRecord.append(getTimelineEmptyDateString());
                            conceptCount++;
                        }
                    }

                    resultFile.append(patientRecord.toString());
                    patientRecord = new StringBuilder();
                    patientCount++;

                    conceptCount = 0;
                    sOldConcept_cd = null;
                    sOldStart_date = null;
                    break;
                } else if (sPatient_num.equals(currentPatientNum)) {
                    indexPos = i + 1;
                    sOldPatient_num = sPatient_num;
                    // if (bUseConcept) {
                    // sConcept_cd =
                    // oChild.getChild(ss_concept_cd).getText();
                    // }
                    // else {
                    // sConcept_cd =
                    // oChild.getAttributeValue(ss_q_name_char);
                    // }

                    if (!sConcept_cd.equals(sOldConcept_cd)) {
                        // conceptCount++;
                        if (bDisplayAll) {
                            for (int j = conceptCount; j < conceptOrder.size(); j++) {
                                if (sConcept_cd.equals(conceptOrder.get(j))) {
                                    break;
                                } else {
                                    patientRecord
                                            .append(getTimelineConceptString((String) conceptOrder.get(j), 1));
                                    patientRecord.append(getTimelineEmptyDateString());
                                    conceptCount++;
                                }
                            }
                        }

                        // int iNumConceptObservations =
                        // getNumConceptObservationsRollingupStartDate
                        // (allChildren,i);

                        // patientRecord.append(getTimelineConceptString(
                        // sConcept_cd,iNumConceptObservations));
                        conceptCount++;
                        sOldStart_date = null;
                    }

                    sOldConcept_cd = sConcept_cd;
                    // sStart_date =
                    // oChild.getChild(ss_start_date).getText();
                    // if (!sStart_date.equals(sOldStart_date)) {
                    // if (!sStart_date.equals(null)) {
                    if ((!sStart_date.equals(null))
                            && ((sOldStart_date == null) || (!sStart_date.equals(sOldStart_date)))) {
                        // sEnd_date =
                        // oChild.getChild(ss_end_date).getText();
                        if ((sEnd_date == null) || (sEnd_date.trim().length() == 0))
                            sEnd_date = sStart_date;
                        // sInout_cd =
                        // oChild.getChild(ss_inout_cd).getText();
                        sInout_cd = "";
                        // sColor = oChild.getChild(ss_color_cd).getText();
                        // sHeight =
                        // oChild.getChild(ss_height_cd).getText();
                        // sValue = oChild.getChild(ss_value_cd).getText();
                        // sTablename =
                        // oChild.getChild(ss_table_name).getText();
                        String prefix = "C";
                        if (sTablename.equalsIgnoreCase("visit_dimension")) {
                            prefix = "E";
                        } else if (sTablename.equalsIgnoreCase("provider_dimension")) {
                            prefix = "P";
                        }

                        // if ((sValue==null)||(sValue.length()==0)) {
                        // sValue = prefix+" = ::"+sConcept_cd+"::"+
                        // "$$"+oChild.getChild(ss_patient_num).getText()+
                        // "$$"+oChild.getChild(ss_concept_cd).getText() +
                        // "$$"+ChangeRsDateFull(sStart_date) ;//+"::";
                    } else {
                        // sValue = prefix+" Value = " +
                        // "::"+sConcept_cd+": "+sValue+"::"+
                        // "$$"+oChild.getChild(ss_patient_num).getText()+
                        // "$$"+oChild.getChild(ss_concept_cd).getText() +
                        // "$$"+ChangeRsDateFull(sStart_date) ;//+"::";
                    }

                    // log.debug("   "+ ChangeRsDate(sStart_date) + " -> " +
                    // ChangeRsDate(sEnd_date));
                    // System.out.print(getTimelineDateString(ChangeRsDate(
                    // sStart_date),ChangeRsDate(sEnd_date)));
                    // System.out.print(getTimelineDateString(ChangeRsDate(
                    // sStart_date),ChangeRsDate(sEnd_date),sConcept_cd));
                    if (sInout_cd.equalsIgnoreCase("I")) {
                        if (sColor != null)
                            patientRecord.append(getTimelineDateStringSpecial(ChangeRsDate(sStart_date),
                                    ChangeRsDate(sEnd_date), sColor));
                        else
                            patientRecord.append(getTimelineDateStringSpecial(ChangeRsDate(sStart_date),
                                    ChangeRsDate(sEnd_date)));
                    } else if (sInout_cd.equalsIgnoreCase("E")) {
                        if (sColor != null)
                            patientRecord.append(getTimelineDateStringEncounter(ChangeRsDate(sStart_date),
                                    ChangeRsDate(sEnd_date), sColor));
                        else
                            patientRecord.append(getTimelineDateStringEncounter(ChangeRsDate(sStart_date),
                                    ChangeRsDate(sEnd_date)));
                    } else if (sInout_cd.equalsIgnoreCase("D")) {
                        if (sStart_date.length() == 0) {
                            if (sColor != null)
                                patientRecord.append(getTimelineDateStringEncounter("today", "today", sColor));
                            else
                                patientRecord.append(getTimelineDateStringEncounter("today", "today"));
                        } else {
                            if (sColor != null)
                                patientRecord.append(
                                        getTimelineDateStringDeath(ChangeRsDate(sStart_date), "today", sColor));
                            else
                                patientRecord.append(
                                        getTimelineDateStringDeath(ChangeRsDate(sStart_date), "today", sColor));
                        }
                    } else {
                        if (sConcept_cd.equals("Death")) {
                            if (sStart_date.length() == 0) {
                                sStart_date = "today";
                                sColor = "lightbrown";
                            }
                            sEnd_date = "today";
                        }
                        if (sColor != null) {
                            if (sConcept_cd.equalsIgnoreCase("EGFR"))
                                patientRecord.append(getTimelineDateString(ChangeRsDate(sStart_date),
                                        ChangeRsDate(sEnd_date), sColor,
                                        "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=gene&cmd=Retrieve&dopt=Graphics&list_uids=1956"));
                            else
                                patientRecord.append(getTimelineDateStringHeight(ChangeRsDate(sStart_date),
                                        ChangeRsDate(sEnd_date), sColor, sHeight, sValue));
                        } else
                            patientRecord.append(getTimelineDateStringHeight(ChangeRsDate(sStart_date),
                                    ChangeRsDate(sEnd_date), sHeight));
                    }
                }
                sOldStart_date = sStart_date;

                if (!bOverMax) {
                    if (bDisplayAll && (indexPos == iNumberOfChildren)) {
                        while ((conceptOrder != null) && (conceptCount < conceptOrder.size())) {
                            patientRecord.append(
                                    getTimelineConceptString((String) conceptOrder.get(conceptCount), 1));
                            patientRecord.append(getTimelineEmptyDateString());
                            conceptCount++;
                        }
                    }
                    resultFile.append(patientRecord.toString());
                    patientRecord = new StringBuilder();
                    patientCount++;
                }
            }
        }

        if ((!bOverMax) && bDisplayAll) {
            while ((conceptOrder != null) && (conceptCount < conceptOrder.size())) {
                patientRecord.append(getTimelineConceptString((String) conceptOrder.get(conceptCount), 1));
                patientRecord.append(getTimelineEmptyDateString());
                conceptCount++;
            }
            resultFile.append(patientRecord.toString());
        }

        resultFile.append(GetTimelineFooter());
        log.debug(" Total Count " + iNumberOfChildren);

        if (writeFile) {
            String i2b2File = System.getProperty("user.dir") + '/' + "i2b2xml.lld";
            File oDelete = new File(i2b2File);
            if (oDelete != null)
                oDelete.delete();
            RandomAccessFile f = new RandomAccessFile(i2b2File, "rw");
            Lib.append(f, resultFile.toString());
            f.close();
        }

        if (bOverMax) {
            log.debug("reached maximum at " + new Date());
            return "overmaximum";
        }
    } catch (java.lang.OutOfMemoryError e) {
        log.error("In resultset builder 6: " + e.getMessage());
        // closeConnection(oConnection);
        return "memory error";
    } catch (Exception e) {
        log.error(e.getMessage());
        // closeConnection(oConnection);
        return "error";
    }

    log.debug("done at " + new Date());
    return resultFile.toString();

}

From source file:mobisocial.noteshere.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 w  w  w . j a  va  2s . c  o m
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.
            }
            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:org.elasticsearch.index.engine.internal.InternalEngine.java

@Override
public void maybeMerge() throws EngineException {
    if (!possibleMergeNeeded) {
        return;//from  w  ww .  ja v  a  2s .co  m
    }
    possibleMergeNeeded = false;
    rwl.readLock().lock();
    try {
        ensureOpen();
        Merges.maybeMerge(indexWriter);
    } 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();
    }
}