Example usage for java.lang System gc

List of usage examples for java.lang System gc

Introduction

In this page you can find the example usage for java.lang System gc.

Prototype

public static void gc() 

Source Link

Document

Runs the garbage collector in the Java Virtual Machine.

Usage

From source file:com.phonegap.Capture.java

/**
 * Called when the video view exits. /*from  www .j a va  2 s  .  c  o m*/
 * 
 * @param requestCode       The request code originally supplied to startActivityForResult(), 
 *                          allowing you to identify who this result came from.
 * @param resultCode        The integer result code returned by the child activity through its setResult().
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 * @throws JSONException 
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // Result received okay
    if (resultCode == Activity.RESULT_OK) {
        // An audio clip was requested
        if (requestCode == CAPTURE_AUDIO) {
            // Get the uri of the audio clip
            Uri data = intent.getData();
            // create a file object from the uri
            results.put(createMediaFile(data));

            if (results.length() >= limit) {
                // Send Uri back to JavaScript for listening to audio
                this.success(new PluginResult(PluginResult.Status.OK, results,
                        "navigator.device.capture._castMediaFile"), this.callbackId);
            } else {
                // still need to capture more audio clips
                captureAudio();
            }
        } else if (requestCode == CAPTURE_IMAGE) {
            // For some reason if I try to do:
            // Uri data = intent.getData();
            // It crashes in the emulator and on my phone with a null pointer exception
            // To work around it I had to grab the code from CameraLauncher.java
            try {
                // Create an ExifHelper to save the exif data that is lost during compression
                ExifHelper exif = new ExifHelper();
                exif.createInFile(DirectoryManager.getTempDirectoryPath(ctx) + "/Capture.jpg");
                exif.readExifData();

                // Read in bitmap of captured image
                Bitmap bitmap = android.provider.MediaStore.Images.Media
                        .getBitmap(this.ctx.getContentResolver(), imageUri);

                // Create entry in media store for image
                // (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
                ContentValues values = new ContentValues();
                values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, IMAGE_JPEG);
                Uri uri = null;
                try {
                    uri = this.ctx.getContentResolver()
                            .insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                } catch (UnsupportedOperationException e) {
                    LOG.d(LOG_TAG, "Can't write to external media storage.");
                    try {
                        uri = this.ctx.getContentResolver()
                                .insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
                    } catch (UnsupportedOperationException ex) {
                        LOG.d(LOG_TAG, "Can't write to internal media storage.");
                        this.fail(createErrorObject(CAPTURE_INTERNAL_ERR,
                                "Error capturing image - no media storage found."));
                        return;
                    }
                }

                // Add compressed version of captured image to returned media store Uri
                OutputStream os = this.ctx.getContentResolver().openOutputStream(uri);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
                os.close();

                bitmap.recycle();
                bitmap = null;
                System.gc();

                // Restore exif data to file
                exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx));
                exif.writeExifData();

                // Add image to results
                results.put(createMediaFile(uri));

                if (results.length() >= limit) {
                    // Send Uri back to JavaScript for viewing image
                    this.success(new PluginResult(PluginResult.Status.OK, results,
                            "navigator.device.capture._castMediaFile"), this.callbackId);
                } else {
                    // still need to capture more images
                    captureImage();
                }
            } catch (IOException e) {
                e.printStackTrace();
                this.fail(createErrorObject(CAPTURE_INTERNAL_ERR, "Error capturing image."));
            }
        } else if (requestCode == CAPTURE_VIDEO) {
            // Get the uri of the video clip
            Uri data = intent.getData();
            // create a file object from the uri
            results.put(createMediaFile(data));

            if (results.length() >= limit) {
                // Send Uri back to JavaScript for viewing video
                this.success(new PluginResult(PluginResult.Status.OK, results,
                        "navigator.device.capture._castMediaFile"), this.callbackId);
            } else {
                // still need to capture more video clips
                captureVideo(duration);
            }
        }
    }
    // If canceled
    else if (resultCode == Activity.RESULT_CANCELED) {
        // If we have partial results send them back to the user
        if (results.length() > 0) {
            this.success(new PluginResult(PluginResult.Status.OK, results,
                    "navigator.device.capture._castMediaFile"), this.callbackId);
        }
        // user canceled the action
        else {
            this.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Canceled."));
        }
    }
    // If something else
    else {
        // If we have partial results send them back to the user
        if (results.length() > 0) {
            this.success(new PluginResult(PluginResult.Status.OK, results,
                    "navigator.device.capture._castMediaFile"), this.callbackId);
        }
        // something bad happened
        else {
            this.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Did not complete!"));
        }
    }
}

From source file:org.asqatasun.service.command.AuditCommandImpl.java

@Override
public void adaptContent() {
    audit = auditDataService.read(audit.getId());
    if (!audit.getStatus().equals(AuditStatus.CONTENT_ADAPTING)) {
        LOGGER.warn(//from w w w  .j  a  v a 2 s.  c o  m
                new StringBuilder(AUDIT_STATUS_IS_LOGGER_STR).append(audit.getStatus()).append(WHILE_LOGGER_STR)
                        .append(AuditStatus.CONTENT_ADAPTING).append(WAS_REQUIRED_LOGGER_STR).toString());
        return;
    }

    LOGGER.info("Adapting " + audit.getSubject().getURL());

    // debug tools
    Date endRetrieveDate;
    Date endProcessDate;
    Date endPersistDate;
    Long persistenceDuration = (long) 0;

    boolean hasCorrectDOM = false;
    Long i = (long) 0;
    Long webResourceId = audit.getSubject().getId();
    Long nbOfContent = contentDataService.getNumberOfSSPFromWebResource(audit.getSubject(), HttpStatus.SC_OK);

    // Some actions have to be realized when the adaptation starts
    if (adaptationListener != null) {
        adaptationListener.adaptationStarted(audit);
    }

    while (i.compareTo(nbOfContent) < 0) {

        LOGGER.debug(new StringBuilder("Adapting ssp from  ").append(i).append(TO_LOGGER_STR)
                .append(i + adaptationTreatmentWindow).append(" for ").append(audit.getSubject().getURL())
                .toString());

        Collection<Content> contentList = contentDataService.getSSPFromWebResource(webResourceId, i,
                adaptationTreatmentWindow, true);
        endRetrieveDate = Calendar.getInstance().getTime();

        Set<Content> contentSet = new HashSet<>();
        // Set the referential to the contentAdapterService due to different
        // behaviour in the implementation. Has to be removed when accessiweb 2.1
        // implementations will be based on jsoup.
        contentSet.addAll(contentAdapterService.adaptContent(contentList));

        endProcessDate = Calendar.getInstance().getTime();
        LOGGER.debug(new StringBuilder("Adapting  ").append(contentList.size()).append(SSP_TOOK_LOGGER_STR)
                .append(endProcessDate.getTime() - endRetrieveDate.getTime()).append(MS_LOGGER_STR)
                .append(contentSet.size()).toString());

        hasCorrectDOM = hasCorrectDOM || hasContentSetAtLeastOneCorrectDOM(contentSet);

        this.encodeSourceAndPersistContentList(contentSet);

        endPersistDate = Calendar.getInstance().getTime();
        LOGGER.debug(new StringBuilder("Persisting  ").append(contentSet.size()).append(SSP_TOOK_LOGGER_STR)
                .append(endPersistDate.getTime() - endProcessDate.getTime()).append(MS_LOGGER_STR)
                .append("for ").append(audit.getSubject().getURL()).toString());
        persistenceDuration = persistenceDuration + (endPersistDate.getTime() - endProcessDate.getTime());
        i = i + adaptationTreatmentWindow;
        // explicit call of the Gc
        System.gc();
    }

    LOGGER.debug(new StringBuilder("Application spent ").append(persistenceDuration)
            .append(" ms to write in Disk while adapting").toString());

    if (hasCorrectDOM) {
        setStatusToAudit(AuditStatus.PROCESSING);
    } else {
        Logger.getLogger(AuditServiceImpl.class).warn("Audit has no corrected DOM");
        setStatusToAudit(AuditStatus.ERROR);
    }

    // Some actions have to be realized when the adaptation is completed
    if (adaptationListener != null) {
        adaptationListener.adaptationCompleted(audit);
    }
    LOGGER.info(audit.getSubject().getURL() + " has been adapted");
}

From source file:com.karura.framework.PluginManager.java

/**
 * Helper function to release all plugins which have been cached in memory. Currently we are also release all pending javascripts and
 * associated messages from the main thread queue
 *//*  w  w  w  .j a v  a2  s  . com*/
private void releasePlugins() {
    // Send onDestroy to all plugins
    for (WebViewPlugin plugin : instanceMap.values()) {
        plugin.onDestory();
    }
    // clear all plugin instances and request system gc
    instanceMap.clear();
    System.gc();

    // clear any pending message queues
    jsMessageQueue.clear();

    // remove any messages which have been posted on the main thread
    mainThread.removeCallbacksAndMessages(null);
}

From source file:com.intuit.wasabi.tests.service.events.TestUserIDLengthForEventCalls.java

@AfterClass
public void tearDown() {
    experiment.state = Constants.EXPERIMENT_STATE_PAUSED;
    putExperiment(experiment);/*w w  w.j a  v  a 2s.co m*/

    // delete the experiment
    experiment.state = Constants.EXPERIMENT_STATE_TERMINATED;
    putExperiment(experiment);

    // lets dereference the experiment and call the Garbage collector Daemon
    experiment = null;
    System.gc();
}

From source file:eu.planets_project.pp.plato.action.ProjectExportAction.java

/**
 * Loads all binary data for the given samplerecord- and upload Ids and dumps it to XML files,  located in tempDir
 *       // w  w  w. ja  v a 2s  .  com
 * @param recordIDs
 * @param uploadIDs
 * @param tempDir
 * @param encoder
 * @throws IOException
 */
private void writeBinaryObjects(List<Integer> recordIDs, List<Integer> uploadIDs, String aTempDir,
        BASE64Encoder encoder) throws IOException {
    int counter = 0;
    int skip = 0;
    List<Integer> allIDs = new ArrayList<Integer>();
    allIDs.addAll(recordIDs);
    allIDs.addAll(uploadIDs);
    log.info("writing XMLs for bytestreams of digital objects. Size = " + allIDs.size());
    for (Integer id : allIDs) {
        if (counter > 200 * 1024 * 1024) { // 200 MB unused stuff lying around
            System.gc();
            counter = 0;
        }
        DigitalObject object = em.find(DigitalObject.class, id);
        if (object.isDataExistent()) {
            counter += object.getData().getSize();
            File f = new File(aTempDir + object.getId() + ".xml");
            writeBinaryData(id, object.getData(), f, encoder);
        } else {
            skip++;
        }
        object = null;
    }
    em.clear();
    System.gc();
    log.info("finished writing bytestreams of digital objects. skipped empty objects: " + skip);
}

From source file:org.jspresso.hrsample.backend.JspressoModelTest.java

/**
 * Tests entities memory consumption./*from ww  w .j  av a2s .  co m*/
 *
 * @throws InterruptedException
 *     the interrupted exception
 */
@Test
public void testEntitiesMemoryConsumption() throws InterruptedException {
    final HibernateBackendController hbc = (HibernateBackendController) getBackendController();
    System.gc();
    //Thread.sleep(2000);
    long start = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
    List<Employee> employees = new ArrayList<>();
    for (int i = 0; i < 5000; i++) {
        Employee emp = hbc.getEntityFactory().createEntityInstance(Employee.class);
        // The employee collection should be sorted by name
        //emp.setName(Integer.toHexString(emp.hashCode()));
        emp.straightSetProperty(IEntity.ID, null);
        employees.add(emp);
    }
    System.gc();
    //Thread.sleep(2000);
    long end = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
    System.out.println((end - start) / 1024 / 1024 + " MB used memory for " + employees.size()
            + " entities. This " + "means " + (end - start) / employees.size() + " B per entity.");
}

From source file:de.fischer.thotti.core.runner.NDRunner.java

private NDTestResult forkNDTestRunnerInSlaveMode(NonDistributedTestType test, TestInstanceType instance)
        throws IOException {
    NDTestResult result = new NDTestResult();
    GregorianCalendar startTime;//from www .ja  va  2 s . c  o  m
    long startTimeMS;
    long endTimeMS;
    int exitCode = -9999;

    result.setTestId(test.getId());
    result.setJVMArgs(instance.getJvmArguments());
    result.setJVMArgsID(instance.getJvmArgsID());
    result.setParamGrpID(instance.getName());

    CommandLine cmdLine = new CommandLine("java");

    if (false == StringUtils.isEmpty(instance.getJvmArguments())) {
        cmdLine.addArguments(instance.getJvmArguments());
    }

    cmdLine.addArgument("-cp").addArgument(System.getProperty("java.class.path"))
            .addArgument(NDRunner.class.getName()).addArgument("--slave").addArgument("--executionid")
            .addArgument(instance.getExecutionID().toString());

    System.gc();
    DefaultExecutor executor = new DefaultExecutor();

    startTime = (GregorianCalendar) Calendar.getInstance();
    startTimeMS = startTime.getTimeInMillis();

    try {
        exitCode = executor.execute(cmdLine);
        result.setSuccessfulTermination(true);
        result.setExitCode(exitCode);
    } catch (ExecuteException e) {
        result.setSuccessfulTermination(false);
        result.setExitCode(e.getExitValue());
    } finally {
        endTimeMS = System.currentTimeMillis();
    }

    result.setExecutionTime(endTimeMS - startTimeMS);
    result.setStartTime(startTime);

    System.out.println(result);

    return result;
}

From source file:com.commander4j.thread.InterfaceThread.java

public void startupInterface() {
    setSessionID(JUnique.getUniqueID());
    Common.sessionID = getSessionID();/*from  w  w w .  j a v a 2 s  .  co  m*/

    Common.sd.setData(getSessionID(), "silentExceptions", "Yes", true);
    Common.applicationMode = "SwingClient";

    JUtility.initLogging("");
    JPrint.init();

    if (JUtility.isValidJavaVersion(Common.requiredJavaVersion) == true) {

        Common.hostList.loadHosts();

        Common.selectedHostID = getHostID();
        houseKeeping = false;

        while (shutdown == false) {

            logger.debug("Connecting to database.");
            while ((Common.hostList.getHost(getHostID()).isConnected(getSessionID()) == false)
                    && (shutdown == false)) {
                Common.hostList.getHost(getHostID()).connect(getSessionID(), getHostID());
            }

            if ((Common.hostList.getHost(getHostID()).isConnected(getSessionID()) == true)
                    && (shutdown == false)) {
                JDBSchema schema = new JDBSchema(getSessionID(), Common.hostList.getHost(getHostID()));

                schema.validate(false);

                JUtility.initEANBarcode();
                JLaunchReport.init();
                Common.init();

                JDBUser user = new JDBUser(getHostID(), getSessionID());
                JDBControl ctrl = new JDBControl(getHostID(), getSessionID());
                JeMail mail = new JeMail(getHostID(), getSessionID());

                user.setUserId("interface");
                user.setPassword("interface");
                user.setLoginPassword("interface");
                Common.userList.addUser(getSessionID(), user);

                enableEnterfaceStatusEmails = Boolean
                        .parseBoolean(ctrl.getKeyValueWithDefault("INTERFACE EMAIL NOTIFY", "false",
                                "Email startup and shutdown events :- true or false"));

                interfaceEmailAddresses = ctrl.getKeyValueWithDefault("INTERFACE ADMIN EMAIL",
                        "someone@somewhere.com", "Email address for startup and shutdown events.");

                StringConverter stringConverter = new StringConverter();
                ArrayConverter arrayConverter = new ArrayConverter(String[].class, stringConverter);
                arrayConverter.setDelimiter(';');
                arrayConverter.setAllowedChars(new char[] { '@', '_' });
                String[] emailList = (String[]) arrayConverter.convert(String[].class, interfaceEmailAddresses);
                siteName = Common.hostList.getHost(getHostID()).getSiteDescription();

                if (user.login()) {

                    if (enableEnterfaceStatusEmails == true) {
                        try {
                            String subject = "";
                            if (houseKeeping == true) {

                            } else {
                                subject = "Commander4j " + JVersion.getProgramVersion()
                                        + " Interface startup for [" + siteName + "] on "
                                        + JUtility.getClientName();
                                mail.postMail(emailList, subject, "Interface service has started.", "", "");
                            }
                        } catch (Exception ex) {
                            logger.error("InterfaceThread Unable to send emails");
                        }
                    }

                    houseKeeping = false;

                    logger.debug("Interface Logged on successfully");

                    logger.debug("Starting Threads....");

                    startupThreads();

                    while ((shutdown == false) & (houseKeeping == false)) {
                        com.commander4j.util.JWait.milliSec(1000);
                        currentDateTime = JUtility.getDateTimeString("yyyy-MM-dd HH:mm:ss");
                        currentDate = currentDateTime.substring(0, 10);
                        currentTime = currentDateTime.substring(11, 19);

                        if (currentTime.substring(0, 5).equals(Common.statusReportTime.substring(0, 5))) {
                            if (currentDate.equals(lastRunDate) == false) {
                                lastRunDate = currentDate;
                                houseKeeping = true;
                            }
                        }

                    }

                    logger.debug("Stopping Threads....");
                    shutdownThreads();

                    user.logout();
                    logger.debug("Interface Logged out successfully");

                    if (enableEnterfaceStatusEmails == true) {
                        try {
                            String subject = "";
                            if (houseKeeping == true) {

                            } else {
                                subject = "Commander4j " + JVersion.getProgramVersion()
                                        + " Interface shutdown for [" + siteName + "] on "
                                        + JUtility.getClientName();
                                mail.postMail(emailList, subject, "Interface service has stopped.", "", "");
                            }
                        } catch (Exception ex) {
                            logger.error("InterfaceThread Unable to send emails");
                        }
                    }

                } else {
                    logger.debug("Interface routine failed to logon to application using account INTERFACE");

                }

                try {
                    backupMessageRetention = Integer.valueOf(ctrl.getKeyValueWithDefault(
                            "INTERFACE BACKUP RETENTION", "30", "NUMBER OF DAYS TO KEEP BACKUP MESSAGES"));
                } catch (Exception ex) {
                    backupMessageRetention = 30;
                }

                String archiveReportString = "";
                if (shutdown == false) {
                    logger.debug("Initiating data archiving....");
                    JDBArchive c = new JDBArchive(getHostID(), getSessionID());
                    c.runSQLJobList();
                    archiveReportString = c.reportData();
                    c = null;
                    logger.debug("Data archiving complete....");

                    logger.debug("Disconnecting from database.");
                    Common.hostList.getHost(getHostID()).disconnectAll();
                }

                if (houseKeeping == true) {
                    logger.debug("HOUSEKEEPING START");

                    // Archive old backup files goes here
                    String archivedFiles = "Backup message files removed by auto archive = ";
                    if (backupMessageRetention > 0) {
                        archivedFiles = archivedFiles + String.valueOf(JArchive.archiveBackupFiles(
                                System.getProperty("user.dir") + File.separator + Common.interface_backup_path,
                                backupMessageRetention));
                    } else {
                        archivedFiles = "Auto archive of messages disabled";
                    }

                    String freeSpace = JUtility.diskFree();

                    String memoryBefore = "Memory used before garbage collection = " + String.valueOf(
                            (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024)
                            + "k";
                    System.gc();
                    String memoryAfter = "Memory used after garbage collection  = " + String.valueOf(
                            (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024)
                            + "k";
                    String stats = GenericMessageHeader.getStats();
                    GenericMessageHeader.clearStats();

                    if (enableEnterfaceStatusEmails == true) {
                        try {
                            mail.postMail(emailList,
                                    "Commander4j " + JVersion.getProgramVersion()
                                            + " Interface maintenance for [" + siteName + "] on "
                                            + JUtility.getClientName(),
                                    memoryBefore + "\n\n" + memoryAfter + "\n\n" + archivedFiles + "\n\n"
                                            + freeSpace + "\n\n" + "Maintenance is scheduled to occur at "
                                            + Common.statusReportTime + " each day.\n\n\n\n" + stats + "\n\n\n"
                                            + archiveReportString,
                                    "", "");
                        } catch (Exception ex) {
                            logger.error("InterfaceThread Unable to send emails");
                        }
                    }
                    logger.debug("Interface Garbage Collection.");
                    logger.debug("HOUSEKEEPING END");

                }
            }
        }
    }
}

From source file:at.stefanproell.ResultSetVerification.ResultSetVerificationAPI.java

public String calculateResultSetHashShort(ResultSet rs, String concatenatedColumns) {

    //@todo hashing

    this.logger.info("Resulset row count: " + this.getResultSetRowCount(rs));

    String resultSetHash = concatenatedColumns;
    String concatenatedIdentifiers = "";

    String currentHash = "";
    String previousKey = "";
    String compositeHash = "";
    int hashCounter = 0;

    long startTime = System.currentTimeMillis();
    //int hashCounter =0;

    try {/* www .  ja  v  a2 s . c om*/

        ResultSetMetaData rsmd = rs.getMetaData();
        int columnsNumber = rsmd.getColumnCount();
        this.logger.info("There are " + columnsNumber + " columns in the result set");

        long meanTimeStart = System.currentTimeMillis();

        rs.setFetchSize(10000);

        while (rs.next()) {
            hashCounter++;
            if (hashCounter % 1000 == 0) {
                long meanTimeStop = System.currentTimeMillis();

                this.logger.warning("Calculated " + hashCounter + " hashes so far. This batch took "
                        + (double) ((meanTimeStop - meanTimeStart) / 1000) + " seconds");

                meanTimeStart = System.currentTimeMillis();
            }

            concatenatedIdentifiers += rs.getString(1);
            //this.logger.info("At row " + hashCounter +" the hash currently has the length of: " + concatenatedIdentifiers.length());

            System.gc();
        }

        resultSetHash += concatenatedIdentifiers;
        this.logger.info("The hash has the length of: " + concatenatedIdentifiers.length());
        resultSetHash = this.calculateHashFromString(resultSetHash);

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    long endTime = System.currentTimeMillis();
    long totalTime = endTime - startTime;
    double elapsedTime = (double) (totalTime / 1000);

    this.logger.info("Calculated " + hashCounter + " hash values in " + elapsedTime + " sec");
    this.logger.info("Hash is " + resultSetHash);
    return resultSetHash;

}

From source file:com.phonegap.customcamera.NativeCameraLauncher.java

@Override
public void run() {

    WindowManager windowManager = (WindowManager) this.cordova.getActivity().getApplicationContext()
            .getSystemService(this.cordova.getActivity().getApplicationContext().WINDOW_SERVICE);
    int rotation = windowManager.getDefaultDisplay().getRotation();

    // Read in bitmap of captured image
    Bitmap bitmap;/*from w  ww  .j  a v a 2s . co m*/
    ExifHelper exif = new ExifHelper();

    //Log.i("orientation", rotation+" rotation");
    int rotate = rotation;
    try {
        // Create an ExifHelper to save the exif data that is lost
        // during compression

        exif.createInFile(getTempDirectoryPath(this.cordova.getActivity().getApplicationContext()) + "/Pic-"
                + this.date + ".jpg");
        exif.readExifData();
        /*Auskommentiert weil es immer auf Querformat gedreht hat*/
        //  rotate = exif.getOrientation();
        Log.i("orientation", rotate + " ");
        //  rotate = 90;

        try {
            bitmap = android.provider.MediaStore.Images.Media
                    .getBitmap(this.cordova.getActivity().getContentResolver(), imageUri);
            Log.i("orientation", bitmap.getWidth() + " " + bitmap.getHeight());
            if (bitmap.getWidth() > bitmap.getHeight()) {
                rotate = rotate + 90;
            }
        } catch (FileNotFoundException e) {
            Uri uri = resultIntent.getData();
            android.content.ContentResolver resolver = this.cordova.getActivity().getContentResolver();
            bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
        }

        // If bitmap cannot be decoded, this may return null
        if (bitmap == null) {
            this.failPicture("Error decoding image.");
            return;
        }

        bitmap = scaleBitmap(bitmap);

        // Add compressed version of captured image to returned media
        // store Uri
        bitmap = getRotatedBitmap(rotate, bitmap, exif);
        //Log.i(LOG_TAG, "URI: " + this.imageUri.toString());
        OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(this.imageUri);
        // ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        // bitmap.compress(CompressFormat.JPEG, this.mQuality, outStream);
        bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
        // String imgString = Base64.encodeToString(outStream.toByteArray(), Base64.NO_WRAP);

        os.close();

        // Restore exif data to file
        exif.createOutFile(this.imageUri.getPath());
        exif.writeExifData();

        // Send Uri back to JavaScript for viewing image
        this.callbackContext
                .sendPluginResult(new PluginResult(PluginResult.Status.OK, this.imageUri.getPath()));
        // this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, imgString));

        bitmap.recycle();
        bitmap = null;
        System.gc();

    } catch (IOException e) {
        e.printStackTrace();
        this.failPicture("Error capturing image.");
    }

}