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.appcelerator.titanium.util.TiUIHelper.java

/**
 * Creates and returns a bitmap for the specified resource ID.
 * @param res_id the bitmap id./*from   w w w  .ja v  a2  s  . c  o m*/
 * @return a new bitmap instance.
 * @module.api
 */
public static Bitmap getResourceBitmap(final int res_id) {
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inPurgeable = true;
    opts.inInputShareable = true;

    Bitmap bitmap = null;
    try {
        bitmap = BitmapFactory.decodeResource(TiApplication.getInstance().getResources(), res_id, opts);
    } catch (OutOfMemoryError e) {
        Log.e(TAG, "Unable to load bitmap. Not enough memory: " + e.getMessage());
    }
    return bitmap;
}

From source file:org.appcelerator.titanium.util.TiUIHelper.java

/**
 * Creates and returns a Bitmap from an InputStream.
 * @param stream an InputStream to read bitmap data.
 * @param opts BitmapFactory options/*  w  w w.j av a  2  s .  c  o  m*/
 * @return a new bitmap instance.
 * @module.api
 */
public static Bitmap createBitmap(InputStream stream, BitmapFactory.Options opts) {
    Rect pad = new Rect();
    if (opts == null) {
        opts = TiBitmapPool.defaultBitmapOptions();
    }
    Bitmap b = null;
    try {
        MarkableInputStream markStream = new MarkableInputStream(stream);
        stream = markStream;

        long mark = markStream.savePosition(65536); // TODO fix this crap.
        markStream.reset(mark);
        TiApplication.getBitmapOptionsTransformer().transformOptions(markStream, opts, mark);
        b = BitmapFactory.decodeResourceStream(null, null, stream, pad, opts);
    } catch (OutOfMemoryError e) {
        Log.e(TAG, "Unable to load bitmap. Not enough memory: " + e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return b;
}

From source file:me.myatminsoe.myansms.Message.java

/**
 * Default constructor.//  w  ww . j  a v a2 s . c om
 *
 * @param context {@link Context} to spawn the {@link SmileyParser}.
 * @param cursor  {@link Cursor} to read the data
 */
private Message(final Context context, final Cursor cursor) {
    id = cursor.getLong(INDEX_ID);
    threadId = cursor.getLong(INDEX_THREADID);
    date = cursor.getLong(INDEX_DATE);
    if (date < ConversationListActivity.MIN_DATE) {
        date *= ConversationListActivity.MILLIS;
    }
    if (cursor.getColumnIndex(PROJECTION_JOIN[INDEX_TYPE]) >= 0) {
        address = cursor.getString(INDEX_ADDRESS);
        body = cursor.getString(INDEX_BODY);
    } else {
        body = null;
        address = null;
    }
    type = cursor.getInt(INDEX_TYPE);
    read = cursor.getInt(INDEX_READ);
    if (body == null) {
        isMms = true;
        try {
            fetchMmsParts(context);
        } catch (OutOfMemoryError e) {
            Log.e(TAG, "error loading parts", e);
            try {
                Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
            } catch (Exception e1) {
                Log.e(TAG, "error creating Toast", e1);
            }
        }
    } else {
        isMms = false;
    }
    try {
        subject = cursor.getString(INDEX_SUBJECT);
    } catch (IllegalStateException e) {
        subject = null;
    }
    try {
        if (cursor.getColumnCount() > INDEX_MTYPE) {
            final int t = cursor.getInt(INDEX_MTYPE);
            if (t != 0) {
                type = t;
            }
        }
    } catch (IllegalStateException e) {
        subject = null;
    }

    // Log.d(TAG, "subject: ", subject);
    // Log.d(TAG, "body: ", body);
    // Log.d(TAG, "type: ", type);
}

From source file:uk.bl.wa.analyser.payload.TikaPayloadAnalyser.java

/**
 * @param source the source of the input stream - typically a WARC file. Used for error logging.
 * @param solr  /*w ww  .j  a  v a  2s  .c om*/
 * @param is  content to analyse.
 * @param url optional URL for the bytes in is.
 * @return
 * @throws IOException
 */
@SuppressWarnings("deprecation")
public SolrRecord extract(String source, SolrRecord solr, InputStream is, String url) throws IOException {

    // Set up the TikaInputStream:
    TikaInputStream tikainput = null;
    if (this.maxBytesToParser > 0) {
        tikainput = TikaInputStream
                .get(new BoundedInputStream(new CloseShieldInputStream(is), maxBytesToParser));
    } else {
        tikainput = TikaInputStream.get(new CloseShieldInputStream(is));
    }

    // Also pass URL as metadata to allow extension hints to work:
    Metadata metadata = new Metadata();
    if (url != null)
        metadata.set(Metadata.RESOURCE_NAME_KEY, url);

    final long detectStart = System.nanoTime();
    StringBuilder detected = new StringBuilder();
    try {
        DetectRunner detect = new DetectRunner(source, tika, tikainput, detected, metadata);
        TimeLimiter.run(detect, 10000L, false);
    } catch (NoSuchFieldError e) {
        // TODO Is this an Apache POI version issue?
        log.error("Tika.detect(): " + e.getMessage() + " for " + url + " in " + source);
        addExceptionMetadata(metadata, new Exception("detect threw " + e.getClass().getCanonicalName()));
    } catch (Exception e) {
        log.error("Tika.detect(): " + e.getMessage() + " for " + url + " in " + source);
        addExceptionMetadata(metadata, e);
    }
    Instrument.timeRel("WARCPayloadAnalyzers.analyze#tikasolrextract", "TikaExtractor.extract#detect",
            detectStart);

    // Only proceed if we have a suitable type:
    if (!this.checkMime(detected.toString())) {
        if ("".equals(detected.toString())) {
            solr.addField(SolrFields.SOLR_CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM.toString());
        } else {
            solr.addField(SolrFields.SOLR_CONTENT_TYPE, detected.toString());
        }
        return solr;
    }

    // Context
    ParseContext context = new ParseContext();
    StringWriter content = new StringWriter();

    // Override the recursive parsing:
    if (embedded == null)
        embedded = new NonRecursiveEmbeddedDocumentExtractor(context);
    context.set(EmbeddedDocumentExtractor.class, embedded);

    try {
        final long parseStart = System.nanoTime();
        ParseRunner runner = new ParseRunner(source, tika.getParser(), tikainput, this.getHandler(content),
                metadata, context);
        try {
            TimeLimiter.run(runner, parseTimeout, true);
        } catch (OutOfMemoryError o) {
            log.error("TikaExtractor.parse() - OutOfMemoryError: " + o.getMessage() + " for " + url + " in "
                    + source);
            addExceptionMetadata(metadata, new Exception("OutOfMemoryError"));
        } catch (RuntimeException r) {
            log.error("TikaExtractor.parse() - RuntimeException: " + r.getMessage() + " for " + url + " in "
                    + source);
            addExceptionMetadata(metadata, r);
        }
        Instrument.timeRel("WARCPayloadAnalyzers.analyze#tikasolrextract", "TikaExtractor.extract#parse",
                parseStart);

        // If there was a parse error, report it:
        String tikaException = metadata.get(TikaPayloadAnalyser.TIKA_PARSE_EXCEPTION);
        if (tikaException != null) {
            solr.addParseException(tikaException, new RuntimeException("Exception from Tika"));
        }

        final long extractStart = System.nanoTime();
        // Copy the body text, forcing a UTF-8 encoding:
        String output = new String(content.toString().getBytes("UTF-8"));
        if (runner.complete || !output.equals("")) {
            if (output.length() > this.max_text_length) {
                output = output.substring(0, this.max_text_length);
            }
            log.debug("Extracted text from: " + url + " in " + source);
            log.debug("Extracted text: " + StringUtils.left(output, 300));
            solr.setField(SolrFields.SOLR_EXTRACTED_TEXT, output);
            solr.setField(SolrFields.SOLR_EXTRACTED_TEXT_LENGTH, Integer.toString(output.length()));
        } else {
            //log.debug("Failed to extract any text from: "+url);
        }

        // Noisily report all metadata properties:
        /*
         * for( String m : metadata.names() ) {
         * log.info("For "+url.substring(url.length() - (int)
         * Math.pow(url.length(),0.85))+": "+m+" -> "+metadata.get(m)); }
         */

        // Attempt to record all metadata discovered:
        if (this.extractAllMetadata) {
            for (String m : metadata.names()) {
                // Ignore these as they are not very interesting:
                if (Metadata.RESOURCE_NAME_KEY.equalsIgnoreCase(m) || "dc:title".equalsIgnoreCase(m)
                        || "title".equalsIgnoreCase(m) || "description".equalsIgnoreCase(m)
                        || "keywords".equalsIgnoreCase(m) || Metadata.CONTENT_ENCODING.equalsIgnoreCase(m)
                        || Metadata.CONTENT_LOCATION.equalsIgnoreCase(m) || "ACTINICTITLE".equalsIgnoreCase(m)
                        || Metadata.CONTENT_TYPE.equalsIgnoreCase(m)) {
                    continue;
                }
                // Record in the document, but trim big ones:
                String value = metadata.get(m);
                if (value != null && value.length() > 100) {
                    value = value.substring(0, 100);
                }
                solr.addField(SolrFields.SOLR_TIKA_METADATA, m + "=" + value);
            }
        }

        // Also Pick out particular metadata:
        String contentType = metadata.get(Metadata.CONTENT_TYPE);
        solr.addField(SolrFields.SOLR_CONTENT_TYPE, contentType);
        solr.addField(SolrFields.SOLR_TITLE, metadata.get(DublinCore.TITLE));
        solr.addField(SolrFields.SOLR_DESCRIPTION, metadata.get(DublinCore.DESCRIPTION));
        solr.addField(SolrFields.SOLR_KEYWORDS, metadata.get("keywords"));
        solr.addField(SolrFields.SOLR_AUTHOR, metadata.get(DublinCore.CREATOR));
        solr.addField(SolrFields.CONTENT_ENCODING, metadata.get(Metadata.CONTENT_ENCODING));

        // Parse out any embedded date that can act as a created/modified date.
        // I was not able find a single example where both created and modified where defined and different. I single field is sufficient.
        String date = null;
        if (metadata.get(Metadata.CREATION_DATE) != null)
            date = metadata.get(Metadata.CREATION_DATE);

        if (metadata.get(Metadata.DATE) != null)
            date = metadata.get(Metadata.DATE);
        if (metadata.get(Metadata.MODIFIED) != null)
            date = metadata.get(Metadata.MODIFIED);
        if (date != null) {
            DateTimeFormatter df = ISODateTimeFormat.dateTimeParser();
            DateTime edate = null;
            try {
                edate = df.parseDateTime(date);
            } catch (IllegalArgumentException e) {
                log.error("Could not parse date: " + date + " from URL " + url + " in " + source);
            }
            if (edate == null) {
                Date javadate = Times.extractDate(date);
                if (javadate != null)
                    edate = new org.joda.time.DateTime(javadate);
            }
            if (edate != null) {
                solr.addField(SolrFields.LAST_MODIFIED_YEAR, "" + edate.getYear());
                DateTimeFormatter iso_df = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC);
                // solr.getSolrDocument().setField(SolrFields.LAST_MODIFIED,
                // edate);
                solr.setField(SolrFields.LAST_MODIFIED, iso_df.print(edate));
            }
        }

        // Also look to record the software identifiers:

        // Look for generic xmp:CreatorTool
        solr.addField(SolrFields.GENERATOR, metadata.get("xmp:CreatorTool"));
        // For PDF, support other metadata tags:
        //solr.addField(SolrFields.GENERATOR, metadata.get( "creator" )); // This appears to be dc:creator i.e. author.
        solr.addField(SolrFields.GENERATOR, metadata.get("producer"));
        solr.addField(SolrFields.GENERATOR, metadata.get(Metadata.SOFTWARE));
        solr.addField(SolrFields.GENERATOR, metadata.get("software"));
        solr.addField(SolrFields.GENERATOR, metadata.get("Software"));
        solr.addField(SolrFields.GENERATOR, metadata.get("generator"));
        solr.addField(SolrFields.GENERATOR, metadata.get("Generator"));
        solr.addField(SolrFields.GENERATOR, metadata.get("ProgId"));

        //handle image EXIF metaformat
        String exifVersion = metadata.get("Exif Version");

        if (exifVersion != null) {
            solr.addField(SolrFields.EXIF_VERSION, exifVersion);
            String exif_artist = metadata.get("Artist");
            if (exif_artist != null) { // This is a better value for the author field
                // This potentially results in multiple author, which is valid
                solr.addField(SolrFields.SOLR_AUTHOR, exif_artist);
            }

            if (this.extractExifLocation) {

                String exif_latitude = metadata.get("GPS Latitude");
                String exif_longitude = metadata.get("GPS Longitude");

                if (exif_latitude != null && exif_longitude != null) {
                    double latitude = DMS2DG(exif_latitude);
                    double longitude = DMS2DG(exif_longitude);

                    try {
                        if (latitude != 0d && longitude != 0d) { // Sometimes they are defined but both 0
                            if (latitude <= 90 && latitude >= -90 && longitude <= 180 && longitude >= -180) {
                                solr.addField(SolrFields.EXIF_LOCATION, latitude + "," + longitude);
                            } else {
                                log.warn(
                                        "invalid gsp exif information:" + exif_latitude + "," + exif_longitude);
                            }

                        }
                    } catch (Exception e) { //Just ignore. No GPS data added to solr
                        log.warn("error parsing exif gps data. latitude:" + exif_latitude + " longitude:"
                                + exif_longitude);
                    }
                }
            }
        }
        //End image exif metadata

        // Application ID, MS Office only AFAICT, and the VERSION is only doc
        String software = null;
        if (metadata.get(Metadata.APPLICATION_NAME) != null)
            software = metadata.get(Metadata.APPLICATION_NAME);
        if (metadata.get(Metadata.APPLICATION_VERSION) != null)
            software += " " + metadata.get(Metadata.APPLICATION_VERSION);
        // Images, e.g. JPEG and TIFF, can have 'Software', 'tiff:Software',
        // PNGs have a 'tEXt tEXtEntry: keyword=Software, value=GPL Ghostscript 8.71'
        String png_textentry = metadata.get("tEXt tEXtEntry");
        if (png_textentry != null && png_textentry.contains("keyword=Software, value="))
            software = png_textentry.replace("keyword=Software, value=", "");
        /* Some JPEGs have this:
        Jpeg Comment: CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), default quality
        comment: CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), default quality
         */
        if (software != null) {
            solr.addField(SolrFields.GENERATOR, software);
        }
        Instrument.timeRel("WARCPayloadAnalyzers.analyze#tikasolrextract", "TikaExtractor.extract#extract",
                extractStart);

    } catch (Exception e) {
        log.error("TikaExtractor.extract(): " + e.getMessage() + " for URL " + url + " in " + source);
    }

    // TODO: This should probably be wrapped in a method-spanning try-finally to guarantee close
    if (tikainput != null) {
        try {
            tikainput.close();
        } catch (IOException e) {
            log.warn("Exception closing TikaInputStream. This leaves tmp-files: " + e.getMessage() + " for "
                    + url + " in " + source);
        }
    }

    return solr;
}

From source file:org.appcelerator.titanium.view.TiDrawableReference.java

/**
 * Gets the bitmap from the resource without respect to sampling/scaling.
 * @return Bitmap, or null if errors occurred while trying to load or fetch it.
 * @module.api/*from   w w w.j  a v a 2s. co m*/
 */
public Bitmap getBitmap() {
    InputStream is = getInputStream();
    if (is == null) {
        Log.w(TAG, "Could not open stream to get bitmap");
        return null;
    }

    Bitmap b = null;

    try {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inInputShareable = true;
        opts.inPurgeable = true;

        try {
            oomOccurred = false;
            b = BitmapFactory.decodeStream(is, null, opts);
        } catch (OutOfMemoryError e) {
            oomOccurred = true;
            Log.e(TAG, "Unable to load bitmap. Not enough memory: " + e.getMessage(), e);
        }

    } finally {
        try {
            is.close();
        } catch (IOException e) {
            Log.e(TAG, "Problem closing stream: " + e.getMessage(), e);
        }
    }

    // Orient the image when orientation is set.
    if (autoRotate) {
        // Only set the orientation if it is uninitialized
        if (orientation < 0) {
            orientation = getOrientation();
        }
        if (orientation > 0) {
            b = getRotatedBitmap(b, orientation);
        }
    }

    return b;
}

From source file:pyromaniac.AcaciaMain.java

/**
 * Run from command line./*from   w w w.  j a  v a2  s.co m*/
 *
 * @param settings the run time settings
 * @throws Exception the exception
 */
private void runFromCommandLine(HashMap<String, String> settings) throws Exception {
    this.checkSettings(settings);

    boolean errorOccurred = false;

    AcaciaLogger logger = new AcaciaLogger();
    try {
        AcaciaEngine engine = AcaciaEngine.getEngine();

        //System.out.println("Initialising the log files");

        //TODO: should not be here, but in runAcacia. Why is it here (and is it something to do with the GUI?)
        //engine.initLogFiles(settings, logger, false, null);

        LinkedList<MIDPrimerCombo> validTags = null;

        if (settings.get(AcaciaConstants.OPT_MID).equals(AcaciaConstants.OPT_LOAD_MIDS)) {
            validTags = engine.loadMIDS(settings.get(AcaciaConstants.OPT_MID_FILE), logger);
        } else {
            validTags = new LinkedList<MIDPrimerCombo>();
            validTags.add(AcaciaConstants.NO_MID_GROUP);
        }

        engine.runAcacia(settings, validTags, logger, null, AcaciaEngine.getVersion(), false);

    } catch (OutOfMemoryError error) {
        errorOccurred = true;
        logger.writeLog(error.getMessage(), AcaciaLogger.LOG_ERROR);

        StackTraceElement[] trace = error.getStackTrace();

        for (int i = 0; i < trace.length; i++) {
            logger.writeLog(trace[i].toString(), AcaciaLogger.LOG_ERROR);
        }
    } catch (Exception e) {
        errorOccurred = true;
        System.out.println(e.getMessage());
        logger.writeLog(e.getMessage(), AcaciaLogger.LOG_ERROR);

        StackTraceElement[] trace = e.getStackTrace();

        for (int i = 0; i < trace.length; i++) {
            logger.writeLog(trace[i].toString(), AcaciaLogger.LOG_ERROR);
        }
    } finally {
        try {
            logger.closeLogger();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (errorOccurred) {
            System.exit(1);
        } else {
            System.exit(0);
        }
    }
}

From source file:com.duroty.service.Mailet.java

/**
 * DOCUMENT ME!/*ww w  .  jav  a 2  s  . c  o m*/
 *
 * @param message DOCUMENT ME!
 * @param exception DOCUMENT ME!
 */
private void sendError(MimeMessage message, Throwable exception) {
    if (true) {
        return;
    }

    StringWriter sw = null;
    PrintWriter writer = null;
    javax.mail.Session msession = null;

    try {
        msession = (javax.mail.Session) ctx.lookup(smtpSessionFactory);

        InternetAddress sender = new InternetAddress("postmaster@duroty.com", "Postmaster");
        InternetAddress errorTo = new InternetAddress(message.getFrom()[0].toString());

        sw = new StringWriter();
        writer = new PrintWriter(sw);

        if (exception != null) {
            exception.printStackTrace(writer);
        }

        //Create the message to forward
        MimeMessage forward = MessageUtilities.createNewMessage(sender, new Address[] { errorTo }, "[ERROR: ",
                " ]", sw.toString(), message, msession);

        //MimeMessage newMessage = MessageUtilities.createForward(sender, forwardTo, message, this.mailSession);
        Thread thread = new Thread(new SendMessageThread(forward));
        thread.start();

        System.gc();
    } catch (Exception e) {
        DLog.log(DLog.ERROR, this.getClass(), "Impossible sent error: " + e.getMessage());
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        DLog.log(DLog.ERROR, this.getClass(), "Impossible sent error: " + ex.getMessage());
    } catch (Throwable e) {
        DLog.log(DLog.ERROR, this.getClass(), "Impossible sent error: " + e.getMessage());
    }
}

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

/**
 * Apply an image with an expected size.
 * A rotation might also be applied if provided.
 * @param anImageUrl the image URI./* w ww.  j av a 2  s .c  om*/
 * @param filename the image filename.
 * @param srcImageSize the source image size
 * @param dstImageSize the expected image size.
 * @param rotationAngle the rotation angle to apply.
 * @return the resized image.
 */
private String resizeImage(String anImageUrl, String filename, ImageSize srcImageSize, ImageSize dstImageSize,
        int rotationAngle) {
    String imageUrl = anImageUrl;

    try {
        // got a dst image size
        if (null != dstImageSize) {
            FileInputStream imageStream = new FileInputStream(new File(filename));

            InputStream resizeBitmapStream = null;

            try {
                resizeBitmapStream = ImageUtils.resizeImage(imageStream, -1,
                        (srcImageSize.mWidth + dstImageSize.mWidth - 1) / dstImageSize.mWidth, 75);
            } catch (OutOfMemoryError ex) {
                Log.e(LOG_TAG, "resizeImage out of memory : " + ex.getMessage());
            } catch (Exception e) {
                Log.e(LOG_TAG, "resizeImage failed : " + e.getMessage());
            }

            if (null != resizeBitmapStream) {
                String bitmapURL = mMediasCache.saveMedia(resizeBitmapStream, null,
                        CommonActivityUtils.MIME_TYPE_JPEG);

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

                resizeBitmapStream.close();
            }
        }

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

    return imageUrl;
}

From source file:org.appcelerator.titanium.view.TiDrawableReference.java

/**
 * Gets the bitmap, scaled to a width & height specified in TiDimension params.
 * @param destWidthDimension (null-ok) TiDimension specifying the desired width.  If .isUnitAuto()
 * then the width will be the source width.  If destWidthDimension is null, then the TiContext
 * will be used to determine the activity window's decor width and use that.
 * @param destHeightDimension (null-ok) TiDimension specifying the desired height.  If .isUnitAuto()
 * then the height will be the source height.  If destHeightDimension is null, then resulting height will
 * be at same ratio to the resulting width as the original height:width.
 * @return Bitmap, or null if any problem getting it.  Check logcat if null.
 *///from   ww  w  .  j a  v  a 2s . c o  m
public Bitmap getBitmap(View parent, TiDimension destWidthDimension, TiDimension destHeightDimension) {
    int srcWidth, srcHeight, destWidth, destHeight;

    Bounds bounds = peekBounds();
    srcWidth = bounds.width;
    srcHeight = bounds.height;

    if (srcWidth <= 0 || srcHeight <= 0) {
        Log.w(TAG, "Bitmap bounds could not be determined. If bitmap is loaded, it won't be scaled.");
        return getBitmap(); // fallback
    }

    if (parent == null) {
        Activity activity = softActivity.get();
        if (activity != null && activity.getWindow() != null) {
            parent = activity.getWindow().getDecorView();
        }
    }

    Bounds destBounds = calcDestSize(srcWidth, srcHeight, destWidthDimension, destHeightDimension, parent);
    destWidth = destBounds.width;
    destHeight = destBounds.height;

    // If src and dest width/height are same, no need to go through all the sampling and scaling jazz.
    if (srcWidth == destWidth && srcHeight == destHeight) {
        return getBitmap();
    }

    if (destWidth <= 0 || destHeight <= 0) {
        // calcDestSize() should actually prevent this from happening, but just in case...
        Log.w(TAG, "Bitmap final bounds could not be determined.  If bitmap is loaded, it won't be scaled.");
        return getBitmap();
    }

    InputStream is = getInputStream();
    if (is == null) {
        Log.w(TAG, "Could not open stream to get bitmap");
        return null;
    }

    Bitmap b = null;
    try {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inInputShareable = true;
        opts.inPurgeable = true;
        opts.inSampleSize = calcSampleSize(srcWidth, srcHeight, destWidth, destHeight);
        if (Log.isDebugModeEnabled()) {
            StringBuilder sb = new StringBuilder();
            sb.append("Bitmap calcSampleSize results: inSampleSize=");
            sb.append(opts.inSampleSize);
            sb.append("; srcWidth=");
            sb.append(srcWidth);
            sb.append("; srcHeight=");
            sb.append(srcHeight);
            sb.append("; finalWidth=");
            sb.append(opts.outWidth);
            sb.append("; finalHeight=");
            sb.append(opts.outHeight);
            Log.d(TAG, sb.toString());
        }

        Bitmap bTemp = null;
        try {
            oomOccurred = false;
            bTemp = BitmapFactory.decodeStream(is, null, opts);
            if (bTemp == null) {
                Log.w(TAG, "Decoded bitmap is null");
                return null;
            }

            if (Log.isDebugModeEnabled()) {
                StringBuilder sb = new StringBuilder();
                sb.append("decodeStream resulting bitmap: .getWidth()=" + bTemp.getWidth());
                sb.append("; .getHeight()=" + bTemp.getHeight());
                sb.append("; getDensity()=" + bTemp.getDensity());
                Log.d(TAG, sb.toString());
            }

            // Set the bitmap density to match the view density before scaling, so that scaling
            // algorithm takes destination density into account.
            DisplayMetrics displayMetrics = new DisplayMetrics();
            displayMetrics.setToDefaults();
            bTemp.setDensity(displayMetrics.densityDpi);

            // Orient the image when orientation is set.
            if (autoRotate) {
                // Only set the orientation if it is uninitialized
                if (orientation < 0) {
                    orientation = getOrientation();
                }
                if (orientation > 0) {
                    return getRotatedBitmap(bTemp, orientation);
                }
            }

            if (bTemp.getNinePatchChunk() != null) {
                // Don't scale nine-patches
                b = bTemp;
                bTemp = null;
            } else {
                Log.d(TAG, "Scaling bitmap to " + destWidth + "x" + destHeight, Log.DEBUG_MODE);

                // If anyDensity=false, meaning Android is automatically scaling
                // pixel dimensions, need to do that here as well, because Bitmap width/height
                // calculations do _not_ do that automatically.
                if (anyDensityFalse && displayMetrics.density != 1f) {
                    destWidth = (int) (destWidth * displayMetrics.density + 0.5f); // 0.5 is to force round up of dimension. Casting to int drops decimals.
                    destHeight = (int) (destHeight * displayMetrics.density + 0.5f);
                }

                // Created a scaled copy of the bitmap. Note we will get
                // back the same bitmap if no scaling is required.
                b = Bitmap.createScaledBitmap(bTemp, destWidth, destHeight, true);
            }

        } catch (OutOfMemoryError e) {
            oomOccurred = true;
            Log.e(TAG, "Unable to load bitmap. Not enough memory: " + e.getMessage(), e);

        } finally {
            // Recycle the temporary bitmap only if it isn't
            // the same instance as our scaled bitmap.
            if (bTemp != null && bTemp != b) {
                bTemp.recycle();
                bTemp = null;
            }
        }

    } finally {
        try {
            is.close();
        } catch (IOException e) {
            Log.e(TAG, "Problem closing stream: " + e.getMessage(), e);
        }
    }
    if (Log.isDebugModeEnabled()) {
        StringBuilder sb = new StringBuilder();
        sb.append("Details of returned bitmap: .getWidth()=" + b.getWidth());
        sb.append("; getHeight()=" + b.getHeight());
        sb.append("; getDensity()=" + b.getDensity());
        Log.d(TAG, sb.toString());
    }
    return b;
}

From source file:com.ichi2.async.Connection.java

private Payload doInBackgroundSync(Payload data) {
    // for for doInBackgroundLoadDeckCounts if any
    sIsCancellable = true;//w w  w  .  j ava  2  s  .c  o  m
    Timber.d("doInBackgroundSync()");
    // Block execution until any previous background task finishes, or timeout after 5s
    boolean ok = DeckTask.waitToFinish(5);

    String hkey = (String) data.data[0];
    boolean media = (Boolean) data.data[1];
    String conflictResolution = (String) data.data[2];
    Collection col = CollectionHelper.getInstance().getCol(AnkiDroidApp.getInstance());

    boolean colCorruptFullSync = false;
    if (!CollectionHelper.getInstance().colIsOpen() || !ok) {
        if (conflictResolution != null && conflictResolution.equals("download")) {
            colCorruptFullSync = true;
        } else {
            data.success = false;
            data.result = new Object[] { "genericError" };
            return data;
        }
    }
    try {
        CollectionHelper.getInstance().lockCollection();
        HttpSyncer server = new RemoteServer(this, hkey);
        Syncer client = new Syncer(col, server);

        // run sync and check state
        boolean noChanges = false;
        if (conflictResolution == null) {
            Timber.i("Sync - starting sync");
            publishProgress(R.string.sync_prepare_syncing);
            Object[] ret = client.sync(this);
            data.message = client.getSyncMsg();
            if (ret == null) {
                data.success = false;
                data.result = new Object[] { "genericError" };
                return data;
            }
            String retCode = (String) ret[0];
            if (!retCode.equals("noChanges") && !retCode.equals("success")) {
                data.success = false;
                data.result = ret;
                // Check if there was a sanity check error
                if (retCode.equals("sanityCheckError")) {
                    // Force full sync next time
                    col.modSchemaNoCheck();
                    col.save();
                }
                return data;
            }
            // save and note success state
            if (retCode.equals("noChanges")) {
                // publishProgress(R.string.sync_no_changes_message);
                noChanges = true;
            } else {
                // publishProgress(R.string.sync_database_acknowledge);
            }
        } else {
            try {
                // Disable sync cancellation for full-sync
                sIsCancellable = false;
                server = new FullSyncer(col, hkey, this);
                if (conflictResolution.equals("upload")) {
                    Timber.i("Sync - fullsync - upload collection");
                    publishProgress(R.string.sync_preparing_full_sync_message);
                    Object[] ret = server.upload();
                    if (ret == null) {
                        data.success = false;
                        data.result = new Object[] { "genericError" };
                        CollectionHelper.getInstance().reopenCollection(); // TODO: is this needed?
                        return data;
                    }
                    if (!ret[0].equals(HttpSyncer.ANKIWEB_STATUS_OK)) {
                        data.success = false;
                        data.result = ret;
                        CollectionHelper.getInstance().reopenCollection(); // TODO: is this needed?
                        return data;
                    }
                } else if (conflictResolution.equals("download")) {
                    Timber.i("Sync - fullsync - download collection");
                    publishProgress(R.string.sync_downloading_message);
                    Object[] ret = server.download();
                    if (ret == null) {
                        data.success = false;
                        data.result = new Object[] { "genericError" };
                        CollectionHelper.getInstance().reopenCollection(); // TODO: is this needed?
                        return data;
                    }
                    if (!ret[0].equals("success")) {
                        data.success = false;
                        data.result = ret;
                        if (!colCorruptFullSync) {
                            CollectionHelper.getInstance().reopenCollection(); // TODO: is this needed?
                        }
                        return data;
                    }
                }
                col = CollectionHelper.getInstance().reopenCollection(); // TODO: is this needed?
            } catch (OutOfMemoryError e) {
                AnkiDroidApp.sendExceptionReport(e, "doInBackgroundSync-fullSync");
                data.success = false;
                data.result = new Object[] { "OutOfMemoryError" };
                return data;
            } catch (RuntimeException e) {
                if (timeoutOccured(e)) {
                    data.result = new Object[] { "connectionError" };
                } else if (e.getMessage().equals("UserAbortedSync")) {
                    data.result = new Object[] { "UserAbortedSync" };
                } else {
                    AnkiDroidApp.sendExceptionReport(e, "doInBackgroundSync-fullSync");
                    data.result = new Object[] { "IOException" };
                }
                data.success = false;
                return data;
            }
        }

        // clear undo to avoid non syncing orphans (because undo resets usn too
        if (!noChanges) {
            col.clearUndo();
        }
        // then move on to media sync
        sIsCancellable = true;
        boolean noMediaChanges = false;
        String mediaError = null;
        if (media) {
            server = new RemoteMediaServer(col, hkey, this);
            MediaSyncer mediaClient = new MediaSyncer(col, (RemoteMediaServer) server, this);
            String ret;
            try {
                ret = mediaClient.sync();
                if (ret == null) {
                    mediaError = AnkiDroidApp.getAppResources().getString(R.string.sync_media_error);
                } else {
                    if (ret.equals("noChanges")) {
                        publishProgress(R.string.sync_media_no_changes);
                        noMediaChanges = true;
                    }
                    if (ret.equals("sanityFailed")) {
                        mediaError = AnkiDroidApp.getAppResources()
                                .getString(R.string.sync_media_sanity_failed);
                    } else {
                        publishProgress(R.string.sync_media_success);
                    }
                }
            } catch (RuntimeException e) {
                if (timeoutOccured(e)) {
                    data.result = new Object[] { "connectionError" };
                } else if (e.getMessage().equals("UserAbortedSync")) {
                    data.result = new Object[] { "UserAbortedSync" };
                } else {
                    AnkiDroidApp.sendExceptionReport(e, "doInBackgroundSync-mediaSync");
                }
                mediaError = e.getLocalizedMessage();
            }
        }
        if (noChanges && (!media || noMediaChanges)) {
            data.success = false;
            data.result = new Object[] { "noChanges" };
            return data;
        } else {
            data.success = true;
            data.data = new Object[] { conflictResolution, col, mediaError };
            return data;
        }
    } catch (MediaSyncException e) {
        Timber.e("Media sync rejected by server");
        data.success = false;
        data.result = new Object[] { "mediaSyncServerError" };
        AnkiDroidApp.sendExceptionReport(e, "doInBackgroundSync");
        return data;
    } catch (UnknownHttpResponseException e) {
        Timber.e("doInBackgroundSync -- unknown response code error");
        e.printStackTrace();
        data.success = false;
        Integer code = e.getResponseCode();
        String msg = e.getLocalizedMessage();
        data.result = new Object[] { "error", code, msg };
        return data;
    } catch (Exception e) {
        // Global error catcher.
        // Try to give a human readable error, otherwise print the raw error message
        Timber.e("doInBackgroundSync error");
        e.printStackTrace();
        data.success = false;
        if (timeoutOccured(e)) {
            data.result = new Object[] { "connectionError" };
        } else if (e.getMessage().equals("UserAbortedSync")) {
            data.result = new Object[] { "UserAbortedSync" };
        } else {
            AnkiDroidApp.sendExceptionReport(e, "doInBackgroundSync");
            data.result = new Object[] { e.getLocalizedMessage() };
        }
        return data;
    } finally {
        // Close collection to roll back any sync failures and
        Timber.d("doInBackgroundSync -- closing collection on outer finally statement");
        col.close(false);
        CollectionHelper.getInstance().unlockCollection();
        Timber.d("doInBackgroundSync -- reopening collection on outer finally statement");
        CollectionHelper.getInstance().reopenCollection();
    }
}