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:es.upv.riromu.arbre.main.MainActivity.java

@Override
protected void onSaveInstanceState(Bundle outState) {
    FileOutputStream fos;// w  w  w . j  a  va  2  s. c  o m

    if (image != null) {
        try {
            String fileName = "temp_image.jpg";
            String fileURL = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                    .getPath() + "/" + fileName;

            fos = new FileOutputStream(fileURL);
            image.compress(Bitmap.CompressFormat.JPEG, compressRatio, fos);
            outState.putBoolean("image", true);
            image.recycle();
            System.gc();
        } catch (Exception e) {
            Log.e(TAG, "Error " + e.getMessage());
        }
    }
    if (state[CROP_IMAGE]) {
        try {
            String fileName = "temp_cropped.jpg";
            String fileURL = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                    .getPath() + "/" + fileName;

            fos = new FileOutputStream(fileURL);
            croppedimage.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            outState.putBoolean("croppedimage", true);
            fos.close();
            croppedimage.recycle();
            System.gc();

        } catch (Exception e) {
            Log.e(TAG, "Error " + e.getMessage());
        }
    }
    if (state[TREAT_IMAGE]) {
        try {
            String fileName = "temp_treated.jpg";
            String fileURL = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                    .getPath() + "/" + fileName;
            fos = new FileOutputStream(fileURL);

            ImageView imv = (ImageView) findViewById(R.id.image_intro);
            ((BitmapDrawable) imv.getDrawable()).getBitmap().compress(Bitmap.CompressFormat.JPEG, 100, fos);
            outState.putBoolean("treatedimage", true);
            fos.close();

        } catch (Exception e) {
            Log.e(TAG, "Error " + e.getMessage());
        }
    }

    if (image_uri != null) {
        outState.putString("image_uri", image_uri.getPath());
    }
    outState.putIntArray("colours", colours);
    outState.putBoolean("cropping", state[CROP_IMAGE]);
    outState.putBoolean("treated", state[TREAT_IMAGE]);

    super.onSaveInstanceState(outState);
}

From source file:co.mwater.foregroundcameraplugin.ForegroundCameraLauncher.java

/**
 * Called when the camera view exits.//ww w.java  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").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // If image available
    if (resultCode == Activity.RESULT_OK) {
        try {
            // Create an ExifHelper to save the exif data that is lost
            // during compression
            ExifHelper exif = new ExifHelper();
            exif.createInFile(
                    getTempDirectoryPath(this.cordova.getActivity().getApplicationContext()) + "/Pic.jpg");
            exif.readExifData();

            // Read in bitmap of captured image
            Bitmap bitmap;
            try {
                bitmap = android.provider.MediaStore.Images.Media
                        .getBitmap(this.cordova.getActivity().getContentResolver(), imageUri);
            } catch (FileNotFoundException e) {
                Uri uri = intent.getData();
                android.content.ContentResolver resolver = this.cordova.getActivity().getContentResolver();
                bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
            }

            bitmap = scaleBitmap(bitmap);

            // 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.cordova.getActivity().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.cordova.getActivity().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.failPicture("Error capturing image - no media storage found.");
                    return;
                }
            }

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

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

            // Send Uri back to JavaScript for viewing image
            this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, uri.toString()));
            //                  getRealPathFromURI(uri, this.cordova))); WRONG. Needs URI

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

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

    // If cancelled
    else if (resultCode == Activity.RESULT_CANCELED) {
        this.failPicture("Camera cancelled.");
    }

    // If something else
    else {
        this.failPicture("Did not complete!");
    }
}

From source file:com.ettrema.zsync.IntegrationTests.java

/**
 * Constructs an UploadMaker/UploadMakerEx, saves the Upload stream to a new File with
 * name uploadFileName, and returns that File.
 * /*from w ww .ja  v a  2s  .  c o  m*/
 * @param localFile The local file to be uploaded
 * @param zsFile The zsync of the server file
 * @param uploadFileName The name of the File in which to save the upload stream
 * @return
 * @throws IOException
 */
private File makeAndSaveUpload(File localFile, File zsFile, String uploadFileName) throws IOException {
    System.out.println("------------- makeAndSaveUpload --------------------");

    System.gc();
    Runtime rt = Runtime.getRuntime();

    UploadMaker umx = new UploadMaker(localFile, zsFile);
    InputStream uploadIn = umx.makeUpload();

    File uploadFile = new File(uploadFileName);

    if (uploadFile.exists()) {
        if (!uploadFile.delete()) {
            throw new RuntimeException("Couldnt delete: " + uploadFile.getAbsolutePath());
        }
    }
    FileOutputStream uploadOut = new FileOutputStream(uploadFile);

    System.gc();
    System.out.println("Memory stats: " + formatBytes(rt.maxMemory()) + " - " + formatBytes(rt.totalMemory())
            + " - " + formatBytes(rt.freeMemory()));
    long endUsed = (rt.totalMemory() - rt.freeMemory());
    System.out.println("Start used memory: " + formatBytes(startUsed) + " end used memory: "
            + formatBytes(endUsed) + " - delta: " + formatBytes(endUsed - startUsed));
    System.out.println("");

    IOUtils.copy(uploadIn, uploadOut);
    uploadIn.close();
    uploadOut.close();

    System.out.println("Created upload of size: " + formatBytes(uploadFile.length()) + " from local file: "
            + formatBytes(localFile.length()));

    return uploadFile;

}

From source file:edu.mayo.informatics.lexgrid.convert.directConversions.UmlsCommon.LoadRRFToDB.java

private static String[] createAndLoadTables(URI rrfLocation, boolean skipNonLexGridFiles,
        boolean recalcRootOnly, String dbServer, String dbDriver, String username, String password,
        LgMessageDirectorIF md, boolean validateMode) throws Exception {
    md.info("Connecting to RRF Files");
    BufferedReader reader = getReader(rrfLocation.resolve("MRFILES.RRF"));

    md.info("Connecting to db Files");
    Connection sqlConnection = DBUtility.connectToDatabase(dbServer, dbDriver, username, password);

    GenericSQLModifier gsm = new GenericSQLModifier(sqlConnection);

    Hashtable columnTypeMap = readMRCols(rrfLocation);
    Hashtable tableColumnMap = new Hashtable();

    List tables = new ArrayList();

    if (skipNonLexGridFiles) {
        // the only tables that I need to load
        tables.add("MRCONSO");
        tables.add("MRDOC");
        tables.add("MRREL");
        tables.add("MRSAB");
        tables.add("MRRANK");

        if (!recalcRootOnly) {
            tables.add("MRDEF");
            tables.add("MRSTY");
            tables.add("MRSAT");
            tables.add("MRHIER");
        }/*from   ww w. j a va 2 s .c  om*/
    }

    md.info("Creating SQL database tables");

    PreparedStatement create = null;
    PreparedStatement drop = null;
    String line = reader.readLine();

    int mrhierHCDCol = -1;
    while (line != null) {
        String[] vals = stringToArray(line, '|');

        // for MRFILES, all I care about is the following
        String file = vals[0];
        String tableName = file.substring(0, file.indexOf('.'));

        // if file is MRHIER, remember HCD column number (base 0)
        if ("MRHIER".equalsIgnoreCase(tableName) && vals.length > 1) {
            mrhierHCDCol = Arrays.asList(vals[2].split(",")).indexOf("HCD");
        }

        if (skipNonLexGridFiles || recalcRootOnly) {
            if (!tables.contains(tableName)) {
                line = reader.readLine();
                continue;
            }
        } else {
            if (file.indexOf('/') != -1) {
                // skip files in subfolders.
                line = reader.readLine();
                continue;
            }
            if (!tables.contains(tableName))
                tables.add(tableName);
        }

        String[] columns = stringToArray(vals[2], ',');

        tableColumnMap.put(file, columns);

        StringBuffer tableCreateSQL = new StringBuffer();
        tableCreateSQL.append("CREATE TABLE {IF NOT EXISTS} ^" + tableName + "^ (");

        for (int i = 0; i < columns.length; i++) {

            tableCreateSQL.append(" ^" + columns[i] + "^ "
                    + mapUMLSType((String) columnTypeMap.get(columns[i] + "|" + file)) + " default NULL,");
        }

        // chop the last comma
        tableCreateSQL.deleteCharAt(tableCreateSQL.length() - 1);
        tableCreateSQL.append(") {TYPE}");

        // make sure the table doesn't exist
        try {
            drop = sqlConnection.prepareStatement(gsm.modifySQL("DROP TABLE " + tableName + " {CASCADE}"));
            drop.executeUpdate();
            drop.close();
        } catch (SQLException e) {
            // most likely means that the table didn't exist.
        }

        create = sqlConnection.prepareStatement(gsm.modifySQL(tableCreateSQL.toString()));
        create.executeUpdate();

        create.close();

        line = reader.readLine();
    }
    reader.close();

    md.info("Creating indexes");

    PreparedStatement createIndex = null;

    createIndex = sqlConnection
            .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi1^ ON ^MRCONSO^ (^CUI^, ^SAB^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection
            .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi2^ ON ^MRCONSO^ (^CUI^, ^AUI^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection
            .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi3^ ON ^MRCONSO^ (^AUI^, ^CODE^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi4^ ON ^MRREL^ (^RELA^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi5^ ON ^MRREL^ (^REL^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi6^ ON ^MRREL^ (^RUI^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection
            .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi7^ ON ^MRREL^ (^SAB^, ^RELA^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi8^ ON ^MRSAB^ (^RSAB^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi9^ ON ^MRRANK^ (^SAB^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi10^ ON ^MRRANK^ (^TTY^)"));
    createIndex.executeUpdate();
    createIndex.close();

    if (!recalcRootOnly) {
        createIndex = sqlConnection
                .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi11^ ON ^MRDEF^ (^CUI^, ^SAB^)"));
        createIndex.executeUpdate();
        createIndex.close();

        createIndex = sqlConnection
                .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi12^ ON ^MRSAT^ (^METAUI^)"));
        createIndex.executeUpdate();
        createIndex.close();

        createIndex = sqlConnection
                .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi13^ ON ^MRSAT^ (^CUI^, ^SAB^)"));
        createIndex.executeUpdate();
        createIndex.close();

        createIndex = sqlConnection
                .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi14^ ON ^MRSAT^ (^CODE^, ^SAB^)"));
        createIndex.executeUpdate();
        createIndex.close();

        createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi15^ ON ^MRSTY^ (^CUI^)"));
        createIndex.executeUpdate();
        createIndex.close();

        createIndex = sqlConnection.prepareStatement(
                gsm.modifySQL("CREATE INDEX ^mi16^ ON ^MRHIER^ (^CUI^, ^AUI^, ^HCD^, ^SAB^, ^CXN^)"));
        createIndex.executeUpdate();
        createIndex.close();

        createIndex = sqlConnection
                .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi17^ ON ^MRHIER^ (^CUI^, ^SAB^, ^CXN^)"));
        createIndex.executeUpdate();
        createIndex.close();
    }

    PreparedStatement insert = null;

    Iterator allTables = tables.iterator();
    Set rootCUIs = new HashSet();
    while (allTables.hasNext()) {
        System.gc();
        String table = (String) allTables.next();
        md.info("Loading " + table);

        boolean loadingMrHier = table.equalsIgnoreCase("MRHIER");

        StringBuffer insertSQL = new StringBuffer();

        insertSQL.append("INSERT INTO " + table + " (");

        String[] vals = (String[]) tableColumnMap.get(table + ".RRF");
        for (int i = 0; i < vals.length; i++) {
            if (gsm.getDatabaseType().equals("ACCESS") && vals[i].equals("VALUE")) {
                // reserved word in MSAccess
                insertSQL.append("\"" + vals[i] + "\", ");
            } else {
                insertSQL.append(vals[i] + ", ");
            }
        }

        // chop the last comma and space
        insertSQL.deleteCharAt(insertSQL.length() - 2);
        insertSQL.append(") VALUES (");

        for (int i = 0; i < vals.length; i++) {
            insertSQL.append("?, ");
        }

        // chop the last comma and space
        insertSQL.deleteCharAt(insertSQL.length() - 2);
        insertSQL.append(")");
        insert = sqlConnection.prepareStatement(gsm.modifySQL(insertSQL.toString()));

        URI tableURI = rrfLocation.resolve(table + ".RRF");

        if (verifyTableExists(tableURI)) {
            try {
                reader = getReader(tableURI);

                int count = 1;
                line = reader.readLine();
                boolean restrictToRootCUIs = recalcRootOnly && table.equalsIgnoreCase("MRCONSO");
                boolean restrictToRootRels = recalcRootOnly && table.equalsIgnoreCase("MRREL");
                while (line != null && line.length() > 0) {
                    // Note: If we are only using the data to recalculate
                    // root nodes,
                    // we only need CUIs defining root hierarchical terms
                    // and any related
                    // relationships.
                    if (restrictToRootCUIs && !line.contains("|SRC|RHT|")) {
                        line = reader.readLine();
                        continue;
                    }
                    String[] data = stringToArray(line, '|');

                    // If processing MRHIER, we only care about entries
                    // relevant to
                    // the specified MRHIER processing option. Many entries
                    // in this file
                    // we do not require since they can be derived from
                    // MRREL.
                    // MRHIER typically is much larger since it pre-computes
                    // the entire
                    // hierarchy, so we want to conserve time and space by
                    // loading only
                    // those entries that require special handling.
                    if (loadingMrHier && mrhierHCDCol > 0 && data.length > mrhierHCDCol
                            && StringUtils.isBlank(data[mrhierHCDCol])) {
                        line = reader.readLine();
                        continue;
                    }

                    if (restrictToRootCUIs && data.length >= 1)
                        rootCUIs.add(data[0]);
                    if (restrictToRootRels && (data.length < 5
                            || (!rootCUIs.contains(data[0]) && !rootCUIs.contains(data[4])))) {
                        line = reader.readLine();
                        continue;
                    }

                    for (int i = 0; i < vals.length; i++) {
                        insert.setString(i + 1, data[i]);
                    }
                    insert.executeUpdate();

                    count++;
                    line = reader.readLine();

                    if (validateMode && count > 100) {
                        line = null;
                    }

                    if (count % 10000 == 0) {
                        md.busy();
                    }

                    if (count % 100000 == 0) {
                        md.info("Loaded " + count + " into " + table);
                    }
                }
                reader.close();
            } catch (Exception e) {
                md.fatalAndThrowException("problem loading the table " + table, e);
            }

        } else {
            md.warn("Could not load table " + table + ". This" + "most likely means the corresponding RRF file"
                    + "was not found in the source.");
        }

        insert.close();
        System.gc();
    }

    sqlConnection.close();
    return (String[]) tables.toArray(new String[tables.size()]);
}

From source file:dpfmanager.shell.modules.threading.core.ThreadingService.java

public void handleGlobalStatus(GlobalStatusMessage gm, boolean silence) {
    if (gm.isNew()) {
        // New file check
        Long uuid = gm.getUuid();
        FileCheck fc = new FileCheck(uuid);
        boolean pending = false;
        if (runningChecks() >= DpFManagerConstants.MAX_CHECKS) {
            // Add pending check
            fc.setInitialTask(gm.getRunnable());
            pendingChecks.add(fc);/*from w w  w.j a  va  2  s  . com*/
            pending = true;
        } else {
            //Start now
            checks.put(uuid, fc);
            context.send(BasicConfig.MODULE_THREADING, new RunnableMessage(uuid, gm.getRunnable()));
        }
        context.send(BasicConfig.MODULE_DATABASE,
                new JobsMessage(JobsMessage.Type.NEW, uuid, gm.getInput(), pending));
    } else if (gm.isInit()) {
        // Init file check
        FileCheck fc = checks.get(gm.getUuid());
        fc.init(gm.getSize(), gm.getConfig(), gm.getInternal(), gm.getInput());
        context.send(BasicConfig.MODULE_MESSAGE, new LogMessage(getClass(), Level.DEBUG,
                bundle.getString("startingCheck").replace("%1", gm.getInput())));
        context.send(BasicConfig.MODULE_DATABASE,
                new JobsMessage(JobsMessage.Type.INIT, fc.getUuid(), fc.getTotal(), fc.getInternal()));
    } else if (gm.isFinish() || gm.isCancel()) {
        // Finish file check
        FileCheck fc = checks.get(gm.getUuid());
        removeZipFolder(fc.getInternal());
        removeDownloadFolder(fc.getInternal());
        moveServerFolder(fc.getUuid(), fc.getInternal());
        if (context.isGui()) {
            // Notify task manager
            needReload = true;
        } else if (!silence) {
            // No ui, show to user
            showToUser(fc.getInternal(), fc.getConfig());
        }
        if (!gm.isCancel()) {
            context.send(BasicConfig.MODULE_DATABASE, new JobsMessage(JobsMessage.Type.FINISH, gm.getUuid()));
        } else {
            removeReportFolderIfEmpty(gm.getInternal());
        }
        checks.remove(gm.getUuid());
        totalChecks++;
        if (totalChecks >= 10) {
            System.gc();
            context.send(BasicConfig.MODULE_MESSAGE,
                    new LogMessage(getClass(), Level.DEBUG, bundle.getString("runGC")));
            totalChecks = 0;
        }
        // Start pending checks
        startPendingChecks();
    } else if (context.isGui() && gm.isReload()) {
        // Ask for reload
        if (needReload) {
            needReload = false;
            context.send(GuiConfig.PERSPECTIVE_REPORTS + "." + GuiConfig.COMPONENT_REPORTS,
                    new ReportsMessage(ReportsMessage.Type.RELOAD));
        }
    }
}

From source file:me.neatmonster.spacertk.PanelListener.java

@Override
public void run() {
    if (mode == 0) {

        try {/*ww w  .j  a v a 2 s.com*/
            serverSocket = new ServerSocket(SpaceRTK.getInstance().rPort, SO_BACKLOG,
                    SpaceRTK.getInstance().bindAddress);
            serverSocket.setSoTimeout(SO_TIMEOUT);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        while (!serverSocket.isClosed()) {
            try {
                final Socket clientSocket = serverSocket.accept();
                new PanelListener(clientSocket);
            } catch (SocketTimeoutException e) {
                // Do nothing.
            } catch (Exception e) {
                if (!e.getMessage().contains("socket closed"))
                    e.printStackTrace();
            }
        }
    } else {
        try {
            final BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String string = input.readLine();
            if (string == null) {
                return;
            }
            string = URLDecoder.decode(string, "UTF-8");
            string = string.substring(5, string.length() - 9);
            final PrintWriter output = new PrintWriter(socket.getOutputStream());
            if (string.startsWith("call") && string.contains("?method=") && string.contains("&args=")) {
                final String method = string.substring(12, string.indexOf("&args="));
                if (string.contains("&key=" + Utilities.crypt(method + SpaceRTK.getInstance().salt))) {
                    if (string.startsWith("call?method=DOWNLOAD_WORLD")) {
                        final boolean wasRunning = RemoteToolkit.isRunning();
                        if (wasRunning)
                            RemoteToolkit.hold();
                        final File file = new File(string.split("\"")[1] + ".zip");
                        ZIP.zip(file, new File(string.split("\"")[1]));
                        if (file.exists()) {
                            final FileInputStream fileInputStream = new FileInputStream(file);
                            final byte[] fileData = new byte[65536];
                            int length;
                            output.println("HTTP/1.1 200 OK");
                            output.println("Content-Type: application/force-download; name=" + file.getName());
                            output.println("Content-Transfer-Encoding: binary");
                            output.println("Content-Length:" + file.length());
                            output.println("Content-Disposition: attachment; filename=" + file.getName());
                            output.println("Expires: 0");
                            output.println("Cache-Control: no-cache, must-revalidate");
                            output.println("Pragma: no-cache");
                            while ((length = fileInputStream.read(fileData)) > 0)
                                output.print(new String(fileData, 0, length));
                            fileInputStream.close();
                        } else
                            output.println(Utilities.addHeader(null));
                        if (wasRunning)
                            RemoteToolkit.unhold();
                    } else {
                        final Object result = interpret(string);
                        if (result != null)
                            try {
                                output.println(Utilities.addHeader(JSONValue.toJSONString(result)));
                            } catch (OutOfMemoryError e) {
                                System.gc();
                                output.println(Utilities.addHeader(null));
                            }
                        else
                            output.println(Utilities.addHeader(null));
                    }
                } else
                    output.println(Utilities.addHeader("Incorrect Salt supplied. Access denied!"));
            } else if (string.startsWith("multiple") && string.contains("?method=")
                    && string.contains("&args=")) {
                final String method = string.substring(16, string.indexOf("&args="));
                if (string.contains("&key=" + Utilities.crypt(method + SpaceRTK.getInstance().salt))) {
                    final Object result = interpretm(string);
                    if (result != null)
                        try {
                            output.println(Utilities.addHeader(JSONValue.toJSONString(result)));
                        } catch (OutOfMemoryError e) {
                            System.gc();
                            output.println(Utilities.addHeader(null));
                        }
                    else
                        output.println(Utilities.addHeader(null));
                } else
                    output.println(Utilities.addHeader("Incorrect Salt supplied. Access denied!"));
            } else if (string.startsWith("ping"))
                output.println(Utilities.addHeader("Pong!"));
            else
                output.println(Utilities.addHeader(null));
            output.flush();
            input.close();
            output.close();
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java

/**
 * Source://from   w  w w.  j  a  va  2 s .c om
 * http://stackoverflow.com/questions/4349075/bitmapfactory-decoderesource
 * -returns-a-mutable-bitmap-in-android-2-2-and-an-immu
 * 
 * Converts a immutable bitmap to a mutable bitmap. This operation doesn't
 * allocates more memory that there is already allocated.
 * 
 * @param imgIn
 *            - Source image. It will be released, and should not be used
 *            more
 * @return a copy of imgIn, but immutable.
 */
public static Bitmap convertBitmapToMutable(Bitmap imgIn) {
    try {
        // this is the file going to use temporally to save the bytes.
        // This file will not be a image, it will store the raw image data.
        File file = new File(MyApp.context.getFilesDir() + File.separator + "temp.tmp");

        // Open an RandomAccessFile
        // Make sure you have added uses-permission
        // android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        // into AndroidManifest.xml file
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");

        // get the width and height of the source bitmap.
        int width = imgIn.getWidth();
        int height = imgIn.getHeight();
        Config type = imgIn.getConfig();

        // Copy the byte to the file
        // Assume source bitmap loaded using options.inPreferredConfig =
        // Config.ARGB_8888;
        FileChannel channel = randomAccessFile.getChannel();
        MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, imgIn.getRowBytes() * height);
        imgIn.copyPixelsToBuffer(map);
        // recycle the source bitmap, this will be no longer used.
        imgIn.recycle();
        System.gc();// try to force the bytes from the imgIn to be released

        // Create a new bitmap to load the bitmap again. Probably the memory
        // will be available.
        imgIn = Bitmap.createBitmap(width, height, type);
        map.position(0);
        // load it back from temporary
        imgIn.copyPixelsFromBuffer(map);
        // close the temporary file and channel , then delete that also
        channel.close();
        randomAccessFile.close();

        // delete the temporary file
        file.delete();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return imgIn;
}

From source file:edu.stanford.mobisocial.dungbeetle.ImageViewerActivity.java

public void onPause() {
    super.onPause();
    if (bitmap != null) {
        bitmap.recycle();
        bitmap = null;
    }
    System.gc();
}

From source file:BenchmarkApplet.java

public static void gc() {
      System.runFinalization();/*from   w w  w  .  j av  a 2s.com*/
      System.gc();
      if (Runtime.getRuntime().freeMemory() < gcMemTarget) {
          try {
              int[] mem = new int[(int) gcMemTarget / 4];
              mem = null;
          } catch (OutOfMemoryError e) {
              gcMemTarget -= 10000;
              recalibrate();
          }
          System.gc();
      }
      try {
          Thread.sleep(100);
      } catch (InterruptedException e) {
      }
  }