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:edu.rit.flick.genetics.FastFileInflator.java

@Override
public synchronized File inflate(final Configuration configuration, final File fileIn, final File fileOut) {
    assert fileIn.exists();

    try {/*  www  . j a va  2 s. c om*/
        // Inflate to Directory
        final String outputDirectoryPath = fileOut.getPath()
                .replaceAll("." + Files.getFileExtension(fileOut.getPath()), FLICK_FAST_FILE_TMP_DIR_SUFFIX);

        final File tmpOutputDirectory = new File(outputDirectoryPath);
        if (tmpOutputDirectory.exists())
            FileUtils.deleteDirectory(tmpOutputDirectory);

        final AtomicReference<Thread> cleanHookAtomic = new AtomicReference<Thread>();

        final Thread inflateToDirectoryThread = new Thread(() -> {
            try {
                // Inflate Fast file to a temporary directory
                inflateFromFile(fileIn, tmpOutputDirectory);

                // Inflate Directory to a zip file
                inflateFromDirectory(tmpOutputDirectory, fileOut);

                // Clean up IO
                close();
                System.gc();
                Thread.sleep(100);

                // Clean up temporary directory
                FileUtils.deleteDirectory(tmpOutputDirectory);

                Runtime.getRuntime().removeShutdownHook(cleanHookAtomic.get());
            } catch (final Exception e) {
                if (!interrupted)
                    System.err.println(e.getMessage());
            }
        }, "Default_Inflation_Thread");

        // Make cleaning hook
        final Thread cleanHook = new Thread(() -> {
            interrupted = true;
            configuration.setFlag(VERBOSE_FLAG, false);
            configuration.setFlag(DELETE_FLAG, false);
            try {
                if (inflateToDirectoryThread.isAlive())
                    inflateToDirectoryThread.interrupt();

                // Clean up IO
                close();
                System.gc();
                Thread.sleep(100);

                synchronized (this) {
                    while (inflateToDirectoryThread.isAlive())
                        this.wait();
                }

            } catch (final IOException | InterruptedException e) {
                e.printStackTrace();
            } finally {
                // Clean up temporary directory
                FileUtils.deleteQuietly(tmpOutputDirectory);
                // Clean up INCOMPLETE output file
                FileUtils.deleteQuietly(fileOut);
                System.out.println();
            }

        }, "Inflation_Cleaning_Thread");

        cleanHookAtomic.set(cleanHook);

        Runtime.getRuntime().addShutdownHook(cleanHook);

        inflateToDirectoryThread.start();
        inflateToDirectoryThread.join();

    } catch (final IOException | InterruptedException e) {
        e.printStackTrace();
    }

    return fileOut;
}

From source file:com.xmobileapp.rockplayer.LastFmAlbumArtImporter.java

/*********************************
 * //from   w  ww . j  a  v a2 s  .c  om
 * Get AlbumArt
 * @throws SAXException 
 * @throws ParserConfigurationException 
 *
 *********************************/
public void getAlbumArt() throws SAXException, ParserConfigurationException {
    /*
     * Initialize Album Cursor
     */
    albumCursor = ((RockPlayer) context).contentResolver.query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
            ((RockPlayer) context).ALBUM_COLS, // we should minimize the number of columns
            null, // all albums 
            null, // parameters to the previous parameter - which is null also 
            null // sort order, SQLite-like
    );

    /*
     * Declare & Initialize some vars
     */
    String artistName = null;
    String albumName = null;
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxParserFactory.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();
    XMLAlbumArtHandler xmlHandler = new XMLAlbumArtHandler();
    //        XMLGoogleAlbumArtHandler xmlGoogleHandler = new XMLGoogleAlbumArtHandler();

    /*
     * Give feedback to the user
     */
    Bundle data = new Bundle();
    Message msg = new Message();
    data.putString("info", "Looking for missing art...");
    msg.setData(data);
    ((RockPlayer) context).getAlbumArtHandler.sendMessage(msg);

    /*
     * Loop through the albums
     */
    albumCursor.moveToFirst();
    for (int i = 0; i < albumCursor.getCount(); i++) {
        System.gc();
        /*
         * Get Album Details
         */
        artistName = albumCursor.getString(albumCursor.getColumnIndex(MediaStore.Audio.Albums.ARTIST));
        albumName = albumCursor.getString(albumCursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM));

        /*
         * If no Art is available fetch it
         */
        if (getAlbumArtPath(artistName, albumName) == null) {
            Log.i("LastFM", "Album with no Art " + albumName);
            try {
                if ((artistName.equals("<unknown>") && albumName.equals("<unknown>"))) {
                    Log.i("ALBUMART", "Unknown album");
                    albumCursor.moveToNext();
                    continue;
                }
            } catch (Exception e) {
                Log.i("ALBUMART", "Null album or artist");
                albumCursor.moveToNext();
                continue;
            }

            /*
             * Give feedback to the user
             */
            data = new Bundle();
            msg = new Message();
            data.putString("info", albumName);
            msg.setData(data);
            ((RockPlayer) context).getAlbumArtHandler.sendMessage(msg);

            String albumArtURL = null;
            try {
                /*
                 * Get album URL from Last.FM
                 */
                String artistNameFiltered = filterString(artistName);
                String albumNameFiltered = filterString(albumName);

                if (USE_GOOGLE_IMAGES) {
                    //                    xmlReader.setContentHandler(xmlGoogleHandler);

                    URL googleImagesRequest = new URL(
                            this.GOOGLE_IMAGES_SEARCH_URL + URLEncoder.encode(artistNameFiltered) + "+"
                                    + URLEncoder.encode(albumNameFiltered));
                    //                    Log.i("GOOGLEIMAGES", googleImagesRequest.toString());

                    //                    DefaultHttpClientConnection httpCon = createGoogleImageConnection(
                    //                          googleImagesRequest.toString());
                    /*
                     * retreive URL
                     */
                    BasicHttpParams params = new BasicHttpParams();
                    HttpConnectionParams.setConnectionTimeout(params, 10000);
                    DefaultHttpClient httpClient = new DefaultHttpClient();

                    // Get cookies from the login page (not the address same of the form post)
                    HttpGet httpGet = new HttpGet(googleImagesRequest.toString());

                    HttpResponse response;

                    try {
                        /*
                         * Get the page
                         */
                        response = httpClient.execute(httpGet);
                        HttpEntity entity = response.getEntity();
                        BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));

                        /*
                         * Parse 1st existing image on the result page
                         */
                        String line;
                        int idxStart = 0;
                        int idxStop;
                        do {
                            line = in.readLine();
                            if (line != null) {
                                //                           Log.i("GIMAGES", line);
                                if (line.startsWith("<table")) {
                                    boolean found = false;
                                    int tries = 0;
                                    while (!found) {
                                        tries++;
                                        if (tries > 12)
                                            break;
                                        idxStart = line.indexOf("<a href=", idxStart);

                                        if (idxStart == -1) {
                                            line = in.readLine();
                                            if (line == null)
                                                break;
                                            continue;
                                        }

                                        idxStart = line.indexOf("http://", idxStart);
                                        idxStop = line.indexOf("&imgrefurl=", idxStart);
                                        albumArtURL = line.substring(idxStart, idxStop);
                                        Log.i("GIMAGE", line.substring(idxStart, idxStop));

                                        try {
                                            //URL albumArt = new URL(URLEncoder.encode(albumArtURL));
                                            //                                    URL albumArt = new URL(albumArtURL);
                                            //                                    InputStream albumArtURLStream = albumArt.openStream();
                                            //                                    albumArtURLStream.close();
                                            if (albumArtURL != null) {
                                                if (createAlbumArt(artistName, albumName,
                                                        albumArtURL) == null) {
                                                    albumArtURL = null;
                                                    found = false;
                                                    Log.i("GIMAGES", "createAlbumArt FAIL");
                                                } else {
                                                    found = true;
                                                    Log.i("GIMAGES", "createAlbumArt WIN");
                                                }
                                            } else {
                                                albumArtURL = null;
                                                found = false;
                                                Log.i("GIMAGES", "albumArt URL FAIL!");
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            albumArtURL = null;
                                            found = false;
                                        }
                                    }
                                    break;
                                }
                            }
                        } while (line != null);

                        //                     xmlReader.parse(new InputSource(in));

                        entity.consumeContent();

                        //                     for(int j = 0; j < xmlGoogleHandler.MAX_IMAGES; j++){
                        //                        if(xmlGoogleHandler.albumArtUrl[j] != null){
                        //                           albumArtURL = xmlGoogleHandler.albumArtUrl[j];
                        //                           break;
                        //                        }
                        //                     }

                        /*
                         * No luck with the duck
                         */
                        //                     if(albumArtURL == null){
                        //                        Log.i("GOOGLEIMAGES", "Absolutely no luck");
                        //                        // mark this as a problematic album... 
                        //                        // so we dont refetch it all the time
                        //                         createSmallAlbumArt(artistName, albumName, false);
                        //                        albumCursor.moveToNext();
                        //                        continue;
                        //                     } else {
                        //                        Log.i("GOOGLEIMAGES", albumArtURL);
                        //                     }

                        /*
                         * Clear up the Handler
                         */
                        //                     xmlGoogleHandler.clear();

                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //                  
                    //                  /*
                    //                  * No Album Art available
                    //                  *  1. try going by the album name
                    //                  *  2. get some artist pic and thats it
                    //                  */
                    //                  if(albumArtURL == null){
                    //                  Log.i("LASTFM", "Could not get album art immediately");
                    //                  Log.i("LASTFM", "Trying sole album search");
                    //                  
                    //                  albumArtURL = getAlbumArtByAlbumName(albumName, artistName);
                    //                  if(albumArtURL == null){
                    //                  Log.i("LASTFM", "Trying to get artist Art");
                    //                  albumArtURL = getArtistArt(artistName);
                    //                  }
                    //                  /*
                    //                  * No luck with the duck
                    //                  */
                    //                  if(albumArtURL == null){
                    //                  Log.i("LASTFM", "Absolutely no luck");
                    //                  // mark this as a problematic album... 
                    //                  // so we dont refetch it all the time
                    //                  createSmallAlbumArt(artistName, albumName, false);
                    //                  albumCursor.moveToNext();
                    //                  continue;
                    //                  }
                    //                  }
                }

                /*
                 * If google images failed try last.fm
                 */
                if (albumArtURL == null) {
                    xmlReader.setContentHandler(xmlHandler);

                    URL lastFmApiRequest = new URL(
                            this.LAST_FM_ALBUM_GETINFO_URL + "&artist=" + URLEncoder.encode(artistNameFiltered)
                                    + "&album=" + URLEncoder.encode(albumNameFiltered));
                    try {
                        BufferedReader in = new BufferedReader(
                                new InputStreamReader(lastFmApiRequest.openStream()));
                        xmlReader.parse(new InputSource(in));

                        if (xmlHandler.xlargeAlbumArt != null) {
                            albumArtURL = xmlHandler.xlargeAlbumArt;
                        } else if (xmlHandler.largeAlbumArt != null) {
                            albumArtURL = xmlHandler.largeAlbumArt;
                        } else if (xmlHandler.mediumAlbumArt != null) {
                            albumArtURL = xmlHandler.mediumAlbumArt;
                        }
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    /*
                     * No Album Art available
                     *  1. try going by the album name
                     *  2. get some artist pic and thats it
                     */
                    if (albumArtURL == null) {
                        Log.i("LASTFM", "Could not get album art immediately");
                        Log.i("LASTFM", "Trying sole album search");

                        albumArtURL = getAlbumArtByAlbumName(albumName, artistName);
                        if (albumArtURL == null) {
                            Log.i("LASTFM", "Trying to get artist Art");
                            albumArtURL = getArtistArt(artistName);
                        }
                        /*
                         * No luck with the duck
                         */
                        if (albumArtURL == null) {
                            Log.i("LASTFM", "Absolutely no luck");
                            // mark this as a problematic album... 
                            // so we dont refetch it all the time
                            createSmallAlbumArt(artistName, albumName, false);
                            albumCursor.moveToNext();
                            continue;
                        }
                    }

                    /* only reaches here if not FAIL */
                    createAlbumArt(artistName, albumName, albumArtURL);

                }

                /*
                 * reset xml handler
                 */
                xmlHandler.smallAlbumArt = null;
                xmlHandler.mediumAlbumArt = null;
                xmlHandler.largeAlbumArt = null;
                xmlHandler.xlargeAlbumArt = null;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }
        /*
         * Create small album art
         */
        createSmallAlbumArt(artistName, albumName, true);

        /*
        * Give feedback to the user
        */
        //Bundle data = new Bundle();
        //Message msg = new Message();
        //data.putString("info", "Creating Thumbnail");
        //msg.setData(data);
        //((Filex) context).getAlbumArtHandler.sendMessage(msg);

        albumCursor.moveToNext();
    }

    /*
     * Give feedback to the user
     */
    data = new Bundle();
    msg = new Message();
    data.putString("info", "Done!");
    msg.setData(data);
    ((RockPlayer) context).getAlbumArtHandler.sendMessage(msg);

    /*
     * Set the last import date on preferences
     */
    //        SharedPreferences settings = ((Filex) this.context).getSharedPreferences(((Filex) this.context).PREFS_NAME, 0);
    //        Editor editor = settings.edit();
    //        editor.putLong("artImportDate", System.currentTimeMillis());
    //        editor.commit();
    RockOnPreferenceManager settings = new RockOnPreferenceManager(
            ((RockPlayer) context).FILEX_PREFERENCES_PATH);
    settings.putLong("artImportDate", System.currentTimeMillis());

    //settings.
    //   long lastAlbumArtImportDate = settings.getLong("artImportDate", 0);
}

From source file:dendroscope.autumn.hybridnumber.ComputeHybridNumber.java

/**
 * close down the thread pool and collect garbage
 *
 * @return best score/*from  w w  w .  ja  va  2 s  .  c  o m*/
 */
protected int done() {
    System.err.println("Best score: " + bestScore.get());
    System.err.println("Time: " + ((System.currentTimeMillis() - startTime) / 1000) + " secs");
    System.err.println("(Size of lookup table: " + lookupTable.size() + ")");
    lookupTable.clear();
    scheduledThreadPoolExecutor.shutdown();
    System.gc();
    return bestScore.get();
}

From source file:dk.statsbiblioteket.util.Files.java

/**
 * Move a file with the same semantics as the standard Unix {@code move}
 * command./*  w w  w  .  ja va  2  s .  c  om*/
 *
 * In contrast to the standard Java {@link File#renameTo} this method
 * does extensive sanity checking and throws appropriate exceptions
 * if something is wrong.
 *
 * This method will cause quite a bit of {@code stat} dancing on the
 * file system, so don't use this method in performance critical regions.
 *
 * If {@code dest} is a directory {@code source} will be moved there keeping
 * its base name.
 * If {@code dest} does not exist {@code source} will be renamed to
 * {@code dest}.
 *
 * @param source    a writable file or directory
 * @param dest      either an existing writable directory, or non-existing file
 *                  with existing parent directory
 * @param overwrite if true and {@code dest} exists and is a regular
 *                  file it will be deleted before moving {@code source}
 *                  here
 * @throws FileNotFoundException      if either {@code source} or the parent
 *                                    directory of {@code dest} does not exist
 * @throws FileAlreadyExistsException if {@code dest} exists and is a
 *                                    regular file. If {@code overwrite}
 *                                    is {@code true} this exception will
 *                                    never be thrown
 * @throws FilePermissionException    if {@code source} or {@code dest} is not
 *                                    writable
 * @throws InvalidFileTypeException   if the parent of {@code dest} is a
 *                                    regular file
 * @throws IOException                if there is an unknown error during the move
 *                                    operation
 */
public static void move(File source, File dest, boolean overwrite) throws IOException {
    if (source == null) {
        throw new NullPointerException("Move source location is null");
    }
    if (dest == null) {
        throw new NullPointerException("Move destination is null");
    }

    /* source checks */
    if (!source.exists()) {
        throw new FileNotFoundException(source.toString());
    }
    if (!source.canWrite()) {
        throw new FilePermissionException(source, Files.Permission.writable);
    }

    /* dest checks */
    File destParent = dest.getParentFile();
    if (dest.exists() && dest.isFile() && !overwrite) {
        throw new FileAlreadyExistsException(dest);
    }
    if (!destParent.exists()) {
        throw new FileNotFoundException("Parent directory of " + dest + " " + "does not exist");
    }
    if (destParent.isFile()) {
        throw new InvalidFileTypeException(destParent, Files.Type.file);
    }
    if (dest.isFile() && !destParent.canWrite()) {
        throw new FilePermissionException(destParent, Files.Permission.writable);
    }

    /* If dest is a dir, move the file into it, keeping the base name */
    if (dest.isDirectory()) {
        if (!dest.canWrite()) {
            throw new FilePermissionException(dest, Files.Permission.writable);
        }
        dest = new File(dest, source.getName());
    }

    if (dest.exists()) {
        if (!overwrite) {
            throw new FileAlreadyExistsException(dest);
        }
        log.trace("Overwriting " + dest);
        Files.delete(dest);
    }

    log.trace("Set to move " + source + " to " + dest);

    // On some platform File.renameTo fails on the first runs. See
    // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6213298
    boolean result = false;
    for (int i = 0; i < 10; i++) {
        result = source.renameTo(dest);
        if (result) {
            break;
        }
        System.gc();
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            // Abort the move operation
            break;
        }
        log.trace("Retrying move (" + i + ")");
    }

    if (!result) {
        log.debug("Atomic move failed. Falling back to copy/delete");
        copy(source, dest, overwrite);
        delete(source);
    }

    log.debug("Moved " + source + " to " + dest);
}

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

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

        try {//from w w  w.  j av  a 2  s .  c om
            serverSocket = new ServerSocket(SpaceBukkit.getInstance().port, SO_BACKLOG,
                    SpaceBukkit.getInstance().bindAddress);
            serverSocket.setSoTimeout(SO_TIMEOUT);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        while (running && !serverSocket.isClosed()) {
            try {
                final Socket clientSocket = serverSocket.accept();
                new PanelListener(clientSocket);
            } catch (SocketTimeoutException e) {
                // Do nothing.
            } catch (IOException e) {
                if (!e.getMessage().toLowerCase().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 + SpaceBukkit.getInstance().salt))) {
                    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 + SpaceBukkit.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.termmed.reconciliation.ChangeConsolidator.java

/**
 * Execute.//from   w w  w .  ja  v a 2s . co  m
 *
 * @throws Exception the exception
 */
public void execute() throws Exception {
    File rels = new File(relationship);
    File relsPrev = new File(relationshipPrevious);

    File folderTmp = new File(rels.getParent() + "/temp");
    if (!folderTmp.exists()) {
        folderTmp.mkdir();
    }
    File sortedfolderTmp = new File(rels.getParent() + "/Sort");
    if (!sortedfolderTmp.exists()) {
        sortedfolderTmp.mkdir();
    }
    File sortedPreviousfile = new File(sortedfolderTmp, "Sort" + relsPrev.getName());
    FileFilterAndSorter fsc = new FileFilterAndSorter(relsPrev, sortedPreviousfile, folderTmp, new int[] { 0 },
            new Integer[] { 8 }, new String[] { "900000000000011006" });
    fsc.execute();
    fsc = null;
    System.gc();

    File sortedExportedfile = new File(sortedfolderTmp, "Sort_" + rels.getName());
    FileSorter fs = new FileSorter(rels, sortedExportedfile, folderTmp, new int[] { 0 });
    fs.execute();
    fs = null;
    System.gc();

    ConsolidateInfRelsSnapshotAndDelta cis = new ConsolidateInfRelsSnapshotAndDelta(FILE_TYPE.RF2_RELATIONSHIP,
            sortedPreviousfile, sortedExportedfile, snapshotFinalFile, deltaFinalFile, releaseDate);
    cis.execute();
    cis = null;
    System.gc();

    if (additionalCharType != null && !additionalCharType.equals("")) {
        File additionalCharTypeFile = new File(additionalCharType);
        File sortedAddfile = new File(sortedfolderTmp, "Sort" + additionalCharTypeFile.getName());
        fsc = new FileFilterAndSorter(additionalCharTypeFile, sortedAddfile, folderTmp, new int[] { 0 },
                new Integer[] { 8 }, new String[] { "900000000000227009" });
        fsc.execute();
        fsc = null;
        System.gc();
        HashSet<File> hFile = new HashSet<File>();

        hFile.add(sortedAddfile);
        hFile.add(snapshotFinalFile);
        CommonUtils.concatFile(hFile, snapshotFinalFile);

        File deltaAddFile = new File(sortedfolderTmp, "Filt" + additionalCharTypeFile.getName());
        fsc = new FileFilterAndSorter(sortedAddfile, deltaAddFile, folderTmp, new int[] { 0 },
                new Integer[] { 1 }, new String[] { releaseDate });
        fsc.execute();
        fsc = null;
        System.gc();
        hFile = new HashSet<File>();

        hFile.add(deltaAddFile);
        hFile.add(deltaFinalFile);
        CommonUtils.concatFile(hFile, deltaFinalFile);

    }
    if (folderTmp.exists()) {
        FileHelper.emptyFolder(folderTmp);
        folderTmp.delete();
    }
    if (sortedfolderTmp.exists()) {
        FileHelper.emptyFolder(sortedfolderTmp);
        sortedfolderTmp.delete();
    }
    if (mergefolderTmp != null && mergefolderTmp.exists()) {
        FileHelper.emptyFolder(mergefolderTmp);
        mergefolderTmp.delete();
    }
}

From source file:com.duroty.task.POP3ServiceTask.java

/**
 * DOCUMENT ME!//from   w  ww . ja v a 2 s . c o  m
 */
private void flush() {
    setInit(true);

    SessionFactory hfactory = null;
    Session hsession = null;
    javax.mail.Session msession = null;

    try {
        hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory);
        hsession = hfactory.openSession();
        msession = (javax.mail.Session) ctx.lookup(durotyMailFactory);

        String pop3Host = msession.getProperty("mail.pop3.host");

        int port = 0;

        try {
            port = Integer.parseInt(msession.getProperty("mail.pop3.port"));
        } catch (Exception ex) {
            port = 0;
        }

        Query query = hsession.getNamedQuery("users-mail");
        query.setBoolean("active", true);
        query.setString("role", "mail");

        ScrollableResults scroll = query.scroll();

        while (scroll.next()) {
            POP3Client client = new POP3Client();

            try {
                if (port > 0) {
                    client.connect(pop3Host, port);
                } else {
                    client.connect(pop3Host);
                }

                client.setState(POP3Client.AUTHORIZATION_STATE);

                //client.setDefaultTimeout()
                Users user = (Users) scroll.get(0);

                String repositoryName = user.getUseUsername();

                if (client.login(repositoryName, user.getUsePassword())) {
                    POP3MessageInfo[] info = client.listUniqueIdentifiers();

                    if ((info != null) && (info.length > 0)) {
                        for (int i = 0; i < info.length; i++) {
                            if (pool.size() >= poolSize) {
                                break;
                            }

                            Reader reader = client.retrieveMessage(info[i].number);

                            boolean existMessage = existMessageName(hfactory.openSession(), user,
                                    info[i].identifier);

                            String key = info[i].identifier + "--" + repositoryName;

                            if (existMessage) {
                                client.deleteMessage(info[i].number);
                            } else {
                                if (!poolContains(key)) {
                                    addPool(key);

                                    MimeMessage mime = buildMimeMessage(info[i].identifier, reader, user);

                                    if (!isSpam(user, mime)) {
                                        client.deleteMessage(info[i].number);

                                        Mailet mailet = new Mailet(this, info[i].identifier, repositoryName,
                                                mime);

                                        Thread thread = new Thread(mailet, key);
                                        thread.start();
                                    } else {
                                        client.deleteMessage(info[i].number);
                                    }
                                }
                            }

                            Thread.sleep(100);
                        }
                    }
                } else {
                }
            } catch (Exception e) {
            } finally {
                System.gc();

                try {
                    client.logout();
                    client.disconnect();
                } catch (Exception e) {
                }
            }
        }
    } catch (Exception e) {
        System.gc();
        pool.clear();
        DLog.log(DLog.ERROR, this.getClass(), e.getMessage());
    } catch (OutOfMemoryError e) {
        System.gc();
        pool.clear();
        DLog.log(DLog.ERROR, this.getClass(), e.getMessage());
    } catch (Throwable e) {
        System.gc();
        pool.clear();
        DLog.log(DLog.ERROR, this.getClass(), e.getMessage());
    } finally {
        System.gc();

        GeneralOperations.closeHibernateSession(hsession);

        setInit(false);
    }
}

From source file:com.twotoasters.android.horizontalimagescroller.io.ImageCacheManager.java

private Bitmap decodeBitmap(InputStream is, int reqWidth, int reqHeight, boolean resampleIsUnnecessary) {
    Bitmap bitmap = null;/*from  w w w.  j  a v a2  s  .co m*/
    try {
        if (resampleIsUnnecessary) {
            bitmap = BitmapFactory.decodeStream(is);
        } else {
            bitmap = BitmapHelper.decodeSampledBitmapFromSteam(new FlushedInputStream(is), reqWidth, reqHeight);
        }
    } catch (OutOfMemoryError e) {
        Log.w(TAG, "Out of memory while decoding bitmap stream");
        System.gc();
    }
    return bitmap;
}

From source file:org.callimachusproject.management.CalliServer.java

public synchronized void start() throws IOException, OpenRDFException {
    running = true;//w ww  .  j a  v a  2s  . co  m
    notifyAll();
    if (server != null) {
        try {
            logger.info("Callimachus is binding to {}", toString());
            for (SetupRealm origin : getRealms()) {
                HttpHost host = URIUtils.extractHost(java.net.URI.create(origin.getRealm()));
                HttpClientFactory.getInstance().setProxy(host, server);
            }
            for (CalliRepository repository : repositories.values()) {
                repository.setCompileRepository(true);
            }
            server.start();
            System.gc();
            Thread.yield();
            long uptime = ManagementFactory.getRuntimeMXBean().getUptime();
            logger.info("Callimachus started after {} seconds", uptime / 1000.0);
            if (listener != null) {
                listener.webServiceStarted(server);
            }
        } catch (IOException e) {
            logger.error(e.toString(), e);
        } catch (OpenRDFException e) {
            logger.error(e.toString(), e);
        }
    }
}

From source file:com.cic.datacrawl.ui.Main.java

private static void startupGUI(String[] args) {
    // ??/*  ww w .jav  a2s  .  c  o  m*/
    boolean isShowChooseWorkspace = true;

    Main main = new Main(SwingGui.FRAME_TITLE);

    if (isShowChooseWorkspace) {
        ChooseWorkspaceDialog dialog = new ChooseWorkspaceDialog(main.debugGui);
        dialog.setStartupArgs(args);
        dialog.setVisible(true);
    }
    Global global = Global.getInstance();

    main.setExitAction(new IProxy(IProxy.EXIT_ACTION));

    main.attachTo(com.cic.datacrawl.ui.shell.Shell.shellContextFactory);

    main.setScope(global);
    main.setGlobal(global);
    main.pack();

    main.startupBrowser();
    main.maxSize();
    if (!isShowChooseWorkspace) {
        main.setVisible(true);
    }

    if (args.length == 2) {
        args = new String[0];
    }

    global.setIn(main.getIn());
    global.setOut(main.getOut());
    global.setErr(main.getErr());

    System.setIn(main.getIn());
    System.setOut(main.getOut());
    System.setErr(main.getErr());

    com.cic.datacrawl.ui.shell.Shell.setDebugGui(main.debugGui);

    final RhinoDim finalDim = main.dim;
    new Thread(new Runnable() {

        @Override
        public void run() {
            while (InitializerRegister.getInstance().isNotFinished())
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }
            ((RunOnStartup) ApplicationContext.getInstance().getBean("runOnStartup")).execute(finalDim);
        }
    }).start();
    new Thread(new Runnable() {

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(60000);
                } catch (InterruptedException e) {
                }
                System.gc();
            }
        }
    }).start();
    // ?
    AutoSaveConfiguration autoSaveRunner = new AutoSaveConfiguration();
    autoSaveRunner.registerSaveRunner(main.debugGui);
    autoSaveRunner.setSleepSecond(3600);
    new Thread(autoSaveRunner).start();

    com.cic.datacrawl.ui.shell.Shell.exec(args, global);
}