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:web.diva.server.model.pca.PCAImageGenerator.java

@SuppressWarnings("CallToPrintStackTrace")
public String toPdfFile(File userFolder, String url) {
    try {/*from ww  w . j a v a 2s .  c  om*/
        BufferedImage pdfImage = image;
        DOMImplementation domImpl = new SVGDOMImplementation();
        String svgNS = "http://www.w3.org/2000/svg";
        SVGDocument svgDocument = (SVGDocument) domImpl.createDocument(svgNS, "svg", null);
        SVGGraphics2D svgGenerator = new SVGGraphics2D(svgDocument);
        svgGenerator.setSVGCanvasSize(new Dimension(pdfImage.getWidth(), pdfImage.getHeight()));
        svgGenerator.setPaint(Color.WHITE);
        svgGenerator.drawImage(pdfImage, 0, 0, null);
        File pdfFile = new File(userFolder, divaDataset.getName() + "_PCA_PLOT" + ".pdf");
        if (!pdfFile.exists()) {
            pdfFile.createNewFile();
        } else {
            pdfFile.delete();
            pdfFile.createNewFile();
        }
        // write the svg file
        File svgFile = new File(pdfFile.getAbsolutePath() + ".temp");
        OutputStream outputStream = new FileOutputStream(svgFile);
        BufferedOutputStream bos = new BufferedOutputStream(outputStream);
        Writer out = new OutputStreamWriter(bos, "UTF-8");

        svgGenerator.stream(out, true /* use css */);
        outputStream.flush();
        outputStream.close();
        bos.close();
        System.gc();
        String svgURI = svgFile.toURI().toString();
        TranscoderInput svgInputFile = new TranscoderInput(svgURI);

        OutputStream outstream = new FileOutputStream(pdfFile);
        bos = new BufferedOutputStream(outstream);
        TranscoderOutput output = new TranscoderOutput(bos);

        //             write as pdf
        Transcoder pdfTranscoder = new PDFTranscoder();
        pdfTranscoder.addTranscodingHint(PDFTranscoder.KEY_PIXEL_UNIT_TO_MILLIMETER, 0.084666f);
        pdfTranscoder.transcode(svgInputFile, output);
        outstream.flush();
        outstream.close();
        bos.close();
        System.gc();
        return url + userFolder.getName() + "/" + pdfFile.getName();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return "";

}

From source file:eu.sisob.uma.restserver.restservices.RESTSERVICEFile.java

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(@FormDataParam("user") String user, @FormDataParam("pass") String pass,
        @FormDataParam("task_code") String task_code, @FormDataParam("files[]") InputStream uploadedInputStream,
        @FormDataParam("files[]") FormDataContentDisposition fileDetail) {
    Response response = null;/*from w w w .  j a  v  a 2 s.  c  om*/

    JSONArray json = new JSONArray();
    if (uploadedInputStream != null && fileDetail != null && user != null && pass != null
            && task_code != null) {
        OutputTaskStatus task_status = TaskManager.getTaskStatus(user, pass, task_code, false, false, false);

        if (task_status.status.equals(OutputTaskStatus.TASK_STATUS_TO_EXECUTE)) {
            //Security
            if (fileDetail.getFileName().contains("\\") || fileDetail.getFileName().contains("/")) {
                response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
                return response;
            }

            File file = new File(
                    AuthorizationManager.TASKS_USERS_PATH + File.separator + user + File.separator + task_code,
                    fileDetail.getFileName());

            long size = 0;
            OutputStream out = null;
            int read = 0;
            byte[] bytes = new byte[1024];
            JSONObject jsono = new JSONObject();

            try {
                out = new FileOutputStream(file);
                while ((read = uploadedInputStream.read(bytes)) != -1) {
                    size += read;
                    out.write(bytes, 0, read);
                }

                jsono.put("name", fileDetail.getFileName());
                jsono.put("size", size);
                jsono.put("url", AuthorizationManager.getGetFileUrl(user, pass, task_code,
                        fileDetail.getFileName(), ""));
                jsono.put("thumbnail_url", "");
                jsono.put("delete_url", AuthorizationManager.getDeleteFileUrl(user, pass, task_code,
                        fileDetail.getFileName(), ""));
                jsono.put("delete_type", "GET");
                json.put(jsono);

                response = Response.status(200).entity(json.toString()).build();
            } catch (IOException e) {
                Logger.getLogger("root").error("Error uploading file (" + file.getAbsolutePath() + ")");
                response = Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                        .entity(TheResourceBundle.getString("Upload Fail")).build();
            } catch (JSONException ex) {
                Logger.getLogger("root").error("Error generatin json (" + file.getAbsolutePath() + ")");
                response = Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                        .entity(TheResourceBundle.getString("Upload Fail")).build();
            } finally {
                try {
                    out.flush();
                    out.close();
                    out = null;
                    System.gc();
                } catch (IOException e) {
                    Logger.getLogger("root").error("Error closing file (" + file.getAbsolutePath() + ")");
                    response = Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                            .entity(TheResourceBundle.getString("Upload Fail")).build();
                }
            }
        } else {
            response = Response.status(Response.Status.PRECONDITION_FAILED).entity(task_status.message).build();
        }
    } else {
        response = Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity(TheResourceBundle.getString("Upload Fail")).build();
    }
    // save it
    //writeToFile(uploadedInputStream, uploadedFileLocation);
    return response;

}

From source file:dk.statsbiblioteket.util.xml.XSLTTest.java

@Test
@Ignore// w w  w  .  j ava 2 s. co m
public void testNoNamespaceSpeed() throws Exception {
    int OUTER = 10;
    int RUNS = 5000;
    URL xslt = XSLTTest.getURL("data/xml/namespace_transform.xslt");
    String input = Files.loadString(new File(XSLTTest.getURL("data/xml/namespace_input.xml").getFile()));

    Profiler profiler = new Profiler(RUNS);
    for (int outer = 0; outer < OUTER; outer++) {

        System.gc();
        profiler.reset();
        for (int i = 0; i < RUNS; i++) {
            Document dom = DOM.stringToDOM(input, false);
            XSLT.transform(xslt, dom, null);
            profiler.beat();
        }
        System.out.println(
                "Speed: " + profiler.getBps(false) + " DOM-using namespace-ignoring transformation/second");

        System.gc();
        profiler.reset();
        for (int i = 0; i < RUNS; i++) {
            Document dom = DOM.stringToDOM(input, true);
            XSLT.transform(xslt, dom, null);
            profiler.beat();
        }
        System.out.println(
                "Speed: " + profiler.getBps(false) + " DOM-using namespace-keeping transformation/second");

        System.gc();
        profiler.reset();
        for (int i = 0; i < RUNS; i++) {
            XSLT.transform(xslt, input, true);
            profiler.beat();
        }
        System.out.println("Speed: " + profiler.getBps(false) + " namespace-ignoring transformation/second");

        System.gc();
        profiler.reset();
        for (int i = 0; i < RUNS; i++) {
            XSLT.transform(xslt, input, false);
            profiler.beat();
        }
        System.out.println("Speed: " + profiler.getBps(false) + " namespace-keeping transformation/second\n");
    }
}

From source file:gov.nist.appvet.tool.sigverifier.Service.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Get received HTTP parameters and file upload
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List items = null;//from w  w w  .jav a 2 s. co m
    FileItem fileItem = null;

    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    // Get received items
    Iterator iter = items.iterator();
    FileItem item = null;

    while (iter.hasNext()) {
        item = (FileItem) iter.next();
        if (item.isFormField()) {
            // Get HTML form parameters
            String incomingParameter = item.getFieldName();
            String incomingValue = item.getString();
            if (incomingParameter.equals("appid")) {
                appId = incomingValue;
            }
            /** CHANGE (START): Get other tools-specific form parameters **/
            /** CHANGE (END): Get other tools-specific form parameters **/
        } else {
            // item should now hold the received file
            if (item != null) {
                fileItem = item;
                log.debug("Received file: " + fileItem.getName());
            }
        }
    }

    if (appId == null) {
        // All tool services require an AppVet app ID
        HttpUtil.sendHttp400(response, "No app ID specified");
        return;
    }

    if (fileItem != null) {
        // Get app file
        fileName = FileUtil.getFileName(fileItem.getName());
        if (!fileName.endsWith(".apk")) {
            HttpUtil.sendHttp400(response, "Invalid app file: " + fileItem.getName());
            return;
        }
        // Create app directory
        appDirPath = Properties.TEMP_DIR + "/" + appId;
        File appDir = new File(appDirPath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        // Create report path
        reportFilePath = Properties.TEMP_DIR + "/" + appId + "/" + reportName + "."
                + Properties.reportFormat.toLowerCase();

        appFilePath = Properties.TEMP_DIR + "/" + appId + "/" + fileName;
        log.debug("App file path: " + appFilePath);
        if (!FileUtil.saveFileUpload(fileItem, appFilePath)) {
            HttpUtil.sendHttp500(response, "Could not save uploaded file");
            return;
        }
    } else {
        HttpUtil.sendHttp400(response, "No app was received.");
        return;
    }

    // Use if reading command from ToolProperties.xml. Otherwise,
    // comment-out if using custom command (called by customExecute())
    command = getCommand();

    // If asynchronous, send acknowledgement back to AppVet now
    if (Properties.protocol.equals(Protocol.ASYNCHRONOUS.name())) {
        HttpUtil.sendHttp202(response, "Received app " + appId + " for processing.");
    }
    /*
     * CHANGE: Select either execute() to execute a native OS command or
     * customExecute() to execute your own custom code. Make sure that the
     * unused method call is commented-out.
     */
    reportBuffer = new StringBuffer();
    boolean succeeded = execute(command, reportBuffer);

    // Delay for demo purposes
    try {
        Thread.sleep(Properties.delay);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // boolean succeeded = customExecute(reportBuffer);
    if (!succeeded) {
        log.error("Error detected: " + reportBuffer.toString());
        String errorReport = ReportUtil.getHtmlReport(response, fileName, ToolStatus.ERROR,
                reportBuffer.toString(), "Description: \tApp is signed.\n\n",
                "Description: \tApp is unsigned or incorrectly signed.\n\n", null,
                "Description: \tError or exception processing app.\n\n");
        // Send report to AppVet
        if (Properties.protocol.equals(Protocol.SYNCHRONOUS.name())) {
            // Send back ASCII in HTTP Response
            ReportUtil.sendInHttpResponse(response, errorReport, ToolStatus.ERROR);
        } else if (Properties.protocol.equals(Protocol.ASYNCHRONOUS.name())) {
            // Send report file in new HTTP Request to AppVet
            if (FileUtil.saveReport(errorReport, reportFilePath)) {
                ReportUtil.sendInNewHttpRequest(appId, reportFilePath, ToolStatus.ERROR);
            }
        }
        return;
    }

    // Analyze report and generate tool status
    log.debug("Analyzing report for " + appFilePath);
    ToolStatus reportStatus = analyzeReport(reportBuffer.toString());
    log.debug("Result: " + reportStatus.name());
    String reportContent = null;

    // Get report
    if (Properties.reportFormat.equals(ReportFormat.HTML.name())) {
        reportContent = ReportUtil.getHtmlReport(response, fileName, reportStatus, reportBuffer.toString(),
                "Description: \tApp is signed (Note: some warnings may exist. See below for details).\n\n",
                "Description: \tApp is unsigned or incorrectly signed.\n\n",
                "Description: \tApp is unsigned or incorrectly signed.\n\n",
                "Description: \tError or exception processing app.\n\n");
    } else if (Properties.reportFormat.equals(ReportFormat.TXT.name())) {
        reportContent = getTxtReport();
    } else if (Properties.reportFormat.equals(ReportFormat.PDF.name())) {
        reportContent = getPdfReport();
    } else if (Properties.reportFormat.equals(ReportFormat.JSON.name())) {
        reportContent = getJsonReport();
    }

    // If report is null or empty, stop processing
    if (reportContent == null || reportContent.isEmpty()) {
        log.error("Tool report is null or empty");
        return;
    }

    // Send report to AppVet
    if (Properties.protocol.equals(Protocol.SYNCHRONOUS.name())) {
        // Send back ASCII in HTTP Response
        ReportUtil.sendInHttpResponse(response, reportContent, reportStatus);
    } else if (Properties.protocol.equals(Protocol.ASYNCHRONOUS.name())) {
        // Send report file in new HTTP Request to AppVet
        if (FileUtil.saveReport(reportContent, reportFilePath)) {
            ReportUtil.sendInNewHttpRequest(appId, reportFilePath, reportStatus);
        }
    }

    // Clean up
    if (!Properties.keepApps) {
        if (FileUtil.deleteDirectory(new File(appDirPath))) {
            log.debug("Deleted " + appFilePath);
        } else {
            log.warn("Could not delete " + appFilePath);
        }
    }

    reportBuffer = null;

    // Clean up
    System.gc();
}

From source file:com.duroty.application.mail.manager.SendManager.java

/**
 * DOCUMENT ME!/*from   ww  w.j  ava 2 s .co  m*/
 *
 * @param hsession DOCUMENT ME!
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param identity DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param cc DOCUMENT ME!
 * @param bcc DOCUMENT ME!
 * @param subject DOCUMENT ME!
 * @param body DOCUMENT ME!
 * @param attachments DOCUMENT ME!
 * @param isHtml DOCUMENT ME!
 * @param charset DOCUMENT ME!
 * @param headers DOCUMENT ME!
 * @param priority DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void send(org.hibernate.Session hsession, Session session, String repositoryName, int ideIdint,
        String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml,
        String charset, InternetHeaders headers, String priority) throws MailException {
    try {
        if (charset == null) {
            charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName());
        }

        if ((body == null) || body.trim().equals("")) {
            body = " ";
        }

        Email email = null;

        if (isHtml) {
            email = new HtmlEmail();
        } else {
            email = new MultiPartEmail();
        }

        email.setCharset(charset);

        Users user = getUser(hsession, repositoryName);
        Identity identity = getIdentity(hsession, ideIdint, user);

        InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName());
        InternetAddress[] _to = MessageUtilities.encodeAddresses(to, null);
        InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null);
        InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null);

        if (_from != null) {
            email.setFrom(_from.getAddress(), _from.getPersonal());
        }

        if (_returnPath != null) {
            email.addHeader("Return-Path", _returnPath.getAddress());
            email.addHeader("Errors-To", _returnPath.getAddress());
            email.addHeader("X-Errors-To", _returnPath.getAddress());
        }

        if (_replyTo != null) {
            email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal());
        }

        if ((_to != null) && (_to.length > 0)) {
            HashSet aux = new HashSet(_to.length);
            Collections.addAll(aux, _to);
            email.setTo(aux);
        }

        if ((_cc != null) && (_cc.length > 0)) {
            HashSet aux = new HashSet(_cc.length);
            Collections.addAll(aux, _cc);
            email.setCc(aux);
        }

        if ((_bcc != null) && (_bcc.length > 0)) {
            HashSet aux = new HashSet(_bcc.length);
            Collections.addAll(aux, _bcc);
            email.setBcc(aux);
        }

        email.setSubject(subject);

        Date now = new Date();

        email.setSentDate(now);

        File dir = new File(System.getProperty("user.home") + File.separator + "tmp");
        if (!dir.exists()) {
            dir.mkdir();
        }

        if ((attachments != null) && (attachments.size() > 0)) {
            for (int i = 0; i < attachments.size(); i++) {
                ByteArrayInputStream bais = null;
                FileOutputStream fos = null;

                try {
                    MailPartObj obj = (MailPartObj) attachments.get(i);

                    File file = new File(dir, obj.getName());

                    bais = new ByteArrayInputStream(obj.getAttachent());
                    fos = new FileOutputStream(file);
                    IOUtils.copy(bais, fos);

                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setPath(file.getPath());
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    attachment.setDescription("File Attachment: " + file.getName());
                    attachment.setName(file.getName());

                    if (email instanceof MultiPartEmail) {
                        ((MultiPartEmail) email).attach(attachment);
                    }
                } catch (Exception ex) {

                } finally {
                    IOUtils.closeQuietly(bais);
                    IOUtils.closeQuietly(fos);
                }
            }
        }

        String mid = getId();

        if (headers != null) {
            Header xheader;
            Enumeration xe = headers.getAllHeaders();

            for (; xe.hasMoreElements();) {
                xheader = (Header) xe.nextElement();

                if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                }
            }
        } else {
            email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">");
            email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">");
        }

        if (priority != null) {
            if (priority.equals("high")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "1");
            } else if (priority.equals("low")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "5");
            }
        }

        if (email instanceof HtmlEmail) {
            ((HtmlEmail) email).setHtmlMsg(body);
        } else {
            email.setMsg(body);
        }

        email.setMailSession(session);

        email.buildMimeMessage();

        MimeMessage mime = email.getMimeMessage();

        int size = MessageUtilities.getMessageSize(mime);

        if (!controlQuota(hsession, user, size)) {
            throw new MailException("ErrorMessages.mail.quota.exceded");
        }

        messageable.saveSentMessage(mid, mime, user);

        Thread thread = new Thread(new SendMessageThread(email));
        thread.start();
    } catch (MailException e) {
        throw e;
    } catch (Exception e) {
        throw new MailException(e);
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        throw new MailException(ex);
    } catch (Throwable e) {
        throw new MailException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:edu.harvard.i2b2.eclipse.plugins.ontology.views.edit.UpdateOntologyDialog.java

public Thread processStatus(ProgressBar bar, Label updateStatus, Button ok, Button background,
        String operationType, boolean includeHiddens) {
    final ProgressBar theBar = bar;
    final Label theStatus = updateStatus;
    final Button theOkButton = ok;
    final Button theBackgroundButton = background;
    final Display theDisplay = Display.getCurrent();
    final String theOperation = operationType;
    final boolean hidden = includeHiddens;

    return new Thread() {
        @Override//w  w  w  .  j  av  a 2  s .  c o m
        public void run() {
            try {
                synchronize(theOperation, hidden, theDisplay);
                if (this.getName().equals("stop")) {
                    System.gc();
                    return;
                }
                long waitTime = 5000; //  msec
                Thread.sleep(waitTime);

                while (ProcessStatus.getInstance().getStatus().getProcessStatusCd().equals("PROCESSING")) {
                    if (this.getName().equals("stop")) {
                        System.gc();
                        return;
                    }
                    // need to do something if this fails...
                    getStatus();
                    String step = ProcessStatus.getInstance().getStatus().getProcessStepCd();
                    if (step.equals("ONT_BUILD_PDO_START")) {
                        if (!(this.getName().equals("stop"))) {
                            theDisplay.syncExec(new Runnable() {
                                public void run() {
                                    theBar.setSelection(33);
                                    theStatus.setText("Building data file to upload");
                                }
                            });
                        }
                    } else if (step.equals("ONT_SENTTO_FRC")) {
                        if (!(this.getName().equals("stop"))) {
                            theDisplay.syncExec(new Runnable() {
                                public void run() {
                                    theBar.setSelection(50);
                                    theStatus.setText("Uploading data file to FRC");
                                }
                            });
                        }
                    } else if (step.equals("ONT_SENTTO_CRCLOADER")) {
                        if (!(this.getName().equals("stop"))) {
                            theDisplay.syncExec(new Runnable() {
                                public void run() {
                                    theBar.setSelection(60);
                                    theStatus.setText("Loading data into dimension table");
                                }
                            });
                        }
                    }
                    if (ProcessStatus.getInstance().getStatus().getProcessStatusCd().equals("COMPLETED")) {
                        if (!(this.getName().equals("stop"))) {
                            theDisplay.syncExec(new Runnable() {
                                public void run() {
                                    theBar.setSelection(100);
                                    theStatus.setText("Synchronization complete");
                                }
                            });
                        }
                        break;
                    }
                    if (ProcessStatus.getInstance().getStatus().getProcessStatusCd().equals("ERROR")) {
                        break;
                    }
                    Thread.sleep(waitTime);
                }
                if (ProcessStatus.getInstance().getStatus().getProcessStatusCd().equals("COMPLETED")) {
                    if (!(this.getName().equals("stop"))) {
                        theDisplay.syncExec(new Runnable() {
                            public void run() {
                                theBar.setSelection(100);
                                theStatus.setText("Synchronization complete");
                                if (theOperation.equals("synchronize_all")) {
                                    theOkButton.setEnabled(false);
                                    MetadataRecord.getInstance().getSyncAction()
                                            .setImageDescriptor(ImageDescriptor.createFromFile(EditView.class,
                                                    "/icons/database_refresh.png"));
                                } else {
                                    theOkButton.setEnabled(false);
                                    if ((ProcessStatus.getInstance()
                                            .getDirtyState() == DirtyValueType.DELETE_EDIT))
                                        MetadataRecord.getInstance().getSyncAction().setImageDescriptor(
                                                ImageDescriptor.createFromFile(EditView.class,
                                                        "/icons/red_database_refresh.png"));
                                    else
                                        MetadataRecord.getInstance().getSyncAction().setImageDescriptor(
                                                ImageDescriptor.createFromFile(EditView.class,
                                                        "/icons/database_refresh.png"));
                                }
                                theBackgroundButton.setEnabled(false);
                            }
                        });
                    }
                }
                if (ProcessStatus.getInstance().getStatus().getProcessStatusCd().equals("ERROR")) {
                    final String errorMessage = "Synchronize process is reporting an error";
                    if (!(this.getName().equals("stop"))) {
                        theDisplay.syncExec(new Runnable() {
                            public void run() {
                                theStatus.setText(errorMessage);
                                theOkButton.setEnabled(true);
                                theBackgroundButton.setEnabled(true);
                            }
                        });

                        java.awt.EventQueue.invokeLater(new Runnable() {
                            public void run() {
                                JOptionPane.showMessageDialog(null, errorMessage, "Error",
                                        JOptionPane.INFORMATION_MESSAGE);
                            }
                        });
                    }
                }
            } catch (InterruptedException e) {
                //         log.error(e.getMessage());
                final String errorMessage = "Synchronize process is reporting a communication error.";
                if (!(this.getName().equals("stop"))) {
                    theDisplay.syncExec(new Runnable() {
                        public void run() {
                            theStatus.setText(errorMessage);
                            theOkButton.setEnabled(true);
                            theBackgroundButton.setEnabled(true);
                        }
                    });
                    java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            JOptionPane.showMessageDialog(null, errorMessage, "Error",
                                    JOptionPane.INFORMATION_MESSAGE);
                        }
                    });
                }

            } catch (Exception e) {
                if (!(this.getName().equals("stop"))) {
                    final String errorMessage = "Synchronize process is reporting an error";
                    theDisplay.syncExec(new Runnable() {
                        public void run() {
                            theStatus.setText(errorMessage);
                            theOkButton.setEnabled(true);
                            theBackgroundButton.setEnabled(true);
                        }
                    });
                    java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            JOptionPane.showMessageDialog(null, errorMessage, "Error",
                                    JOptionPane.INFORMATION_MESSAGE);
                        }
                    });
                }
            } finally {
                //   interrupt();

            }

        }
    };
}

From source file:com.slytechs.capture.file.editor.FileEditorImpl.java

/**
 * <p>//from   w  w w  . ja va 2  s . co m
 * Flushes all the changes that currently exist in the "edits" buffer into a
 * temporary secondary file. After the copy the original file is removed and
 * the temporary file is renamed back to the original file which now contains
 * the contents of the "edits" buffer.
 * </p>
 * <p>
 * All the regions and their overlays are iterated over one segment at a time,
 * this includes the big segment consiting of the original file content, and
 * their reader's are asked to copy their buffers out to the temporary file's
 * channel in their individual smaller segments.
 * </p>
 * 
 * @throws IOException
 *           any IO errors with either the source file or the temporary file
 *           operation's during the flush
 */
private void flushByCopy() throws IOException {

    /*
     * Create a temp file
     */

    final File temp = File.createTempFile(this.file.getName(), null);

    final FileChannel tempChannel = new RandomAccessFile(temp, "rw").getChannel();

    /*
     * Copy entire edits tree, including the root file, to temp file
     */
    for (final RegionSegment<PartialLoader> segment : this.edits) {
        final PartialLoader loader = new ConstrainedPartialLoader(segment.getData(), segment);

        loader.transferTo(tempChannel);
    }
    this.channel.close();
    tempChannel.close();

    System.gc();

    /*
     * We're done with the original file. All changes are now in the temp file
     * Try rename first, if it doesn't exist then do it by copy
     */
    if (file.delete() == false) {
        throw new IOException("Unable to delete original file during flushByCopy()");
    }
    if (temp.renameTo(file) == false) {
        throw new IOException("Unable to move temporary file during flushByCopy()");
    }

    final String accessMode = (mode.isContent() ? "rw" : "r");

    /*
     * Now we need to reopen the channel
     */
    this.channel = new RandomAccessFile(file, accessMode).getChannel();
}

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

private void putBitmapToCaches(InputStream is, ImageUrlRequest imageUrlRequest) throws IOException {
    FlushedInputStream fis = new FlushedInputStream(is);
    Bitmap bitmap = null;//  w  w  w.jav  a2s.  c  o  m
    try {
        bitmap = BitmapHelper.decodeSampledBitmapFromSteam(fis, imageUrlRequest.getReqWidth(),
                imageUrlRequest.getReqHeight());
        memoryCache.put(imageUrlRequest.getCacheKey(), bitmap);
    } catch (OutOfMemoryError e) {
        Log.v(TAG, "writeToExternalStorage - Out of memory");
        System.gc();
    }

    if (bitmap != null) {
        createFileIfNonexistent(imageUrlRequest);
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(openImageFileByUrl(imageUrlRequest)), 65535);
        bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
        bos.flush();
        bos.close();
    }
    fis.close();
    is.close();
}

From source file:ffx.potential.nonbonded.PMEWisdom.java

private long findPMEGridSpacing(double cutoff, double alpha, int order, double initial,
        double gradientTolerance) {
    double spacing = initial - 0.1;
    double previousRMS = 0.0;
    double rms = 0.0;
    NeighborList neighborList = new NeighborList(null, crystal, atoms, cutoff, buffer, parallelTeam);
    neighborList.buildList(coordinates, neighborLists, null, true, false);

    logger.setLevel(Level.INFO);//from ww  w  .  j  a  va2 s .c  o m
    logger.info(String.format("RMS Gradient Tolerance: %5.3f\n", gradientTolerance));

    while (rms < gradientTolerance) {
        previousRMS = rms;
        // Increase the grid spacing until the rms force error is too large.
        spacing += 0.1;
        logger.info(String.format("Evaluating Grid Spacing: %5.3f\n", spacing));
        forceField.addForceFieldDouble(ForceFieldDouble.EWALD_CUTOFF, cutoff);
        forceField.addForceFieldDouble(ForceFieldDouble.EWALD_ALPHA, alpha);
        forceField.addForceFieldDouble(ForceFieldDouble.PME_MESH_DENSITY, spacing);
        forceField.addForceFieldInteger(ForceFieldInteger.PME_ORDER, order);
        ParticleMeshEwaldCart particleMeshEwald = null;
        //ParticleMeshEwald particleMeshEwald = new ParticleMeshEwald(
        //        molecularAssembly, crystal, neighborList, ELEC_FORM.PAM, parallelTeam);

        System.gc();
        particleMeshEwald.energy(true, false);
        particleMeshEwald.getGradients(gradients);
        /* Calculate the RMS gradient error. */
        double denom = 0.0;
        for (int i = 0; i < nAtoms; i++) {
            double hxi = hx[i];
            double hyi = hy[i];
            double hzi = hz[i];
            double dx = hxi - gx[i];
            double dy = hyi - gy[i];
            double dz = hzi - gz[i];
            rms += dx * dx;
            rms += dy * dy;
            rms += dz * dz;
            denom += hxi * hxi + hyi * hyi + hzi * hzi;
        }
        rms = Math.sqrt(rms / denom);
        logger.info(String.format("RMS Gradient Error:     %6.3e (%6.3e percent of maximum)\n", rms,
                rms / gradientTolerance * 100));
    }
    spacing -= 0.1;

    // Find the best timing for these PME parameters.
    forceField.addForceFieldDouble(ForceFieldDouble.EWALD_CUTOFF, cutoff);
    forceField.addForceFieldDouble(ForceFieldDouble.EWALD_ALPHA, alpha);
    forceField.addForceFieldDouble(ForceFieldDouble.PME_MESH_DENSITY, spacing);
    forceField.addForceFieldInteger(ForceField.ForceFieldInteger.PME_ORDER, order);

    ParticleMeshEwaldCart particleMeshEwald = null;
    // ParticleMeshEwald particleMeshEwald = new ParticleMeshEwald(
    //        molecularAssembly, crystal, neighborList, ELEC_FORM.PAM, parallelTeam);

    System.gc();
    long bestTime = System.nanoTime();
    particleMeshEwald.energy(true, false);
    bestTime = System.nanoTime() - bestTime;
    long newTime = bestTime;
    for (int i = 0; i < 5; i++) {
        newTime = System.nanoTime();
        if (i == 4) {
            logger.setLevel(Level.FINE);
        }
        particleMeshEwald.energy(true, false);
        if (i == 4) {
            logger.setLevel(Level.INFO);
        }
        newTime = System.nanoTime() - newTime;
        if (newTime < bestTime) {
            bestTime = newTime;
        }
    }

    StringBuilder sb = new StringBuilder();
    sb.append(String.format("\nRMS Gradient Tolerance: %6.3e\n", gradientTolerance));
    sb.append(String.format("RMS Gradient Error:     %6.3e\n", previousRMS));
    sb.append(String.format("Ewald Coefficient:      %5.3f\n", alpha));
    sb.append(String.format("Real Space Cutoff:      %5.3f\n", cutoff));
    sb.append(String.format("Grid Spacing:           %5.3f\n", spacing));
    sb.append(String.format("Time:                   %5.3f\n", bestTime * toSeconds));
    logger.info(sb.toString());
    return bestTime;
}

From source file:de.dal33t.powerfolder.PowerFolder.java

/**
 * Starts a PowerFolder controller with the given command line arguments
 *
 * @param args//w ww .j ava2  s.  com
 */
public static void startPowerFolder(String[] args) {

    // Touch Logger immediately to initialize handlers.
    LoggingManager.isLogToFile();

    // Default exception logger
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            e.printStackTrace();
            log.log(Level.SEVERE, "Exception in " + t + ": " + e.toString(), e);
        }
    });

    CommandLine commandLine = parseCommandLine(args);
    if (commandLine == null) {
        return;
    }

    // -l --log console log levels (severe, warning, info, fine and finer).
    if (commandLine.hasOption("l")) {
        String levelName = commandLine.getOptionValue("l");
        Level level = LoggingManager.levelForName(levelName);
        if (level != null) {
            LoggingManager.setConsoleLogging(level);
        }
    }

    if (commandLine.hasOption("s")) {
        // Server mode, suppress debug output on console
        // Logger.addExcludeConsoleLogLevel(Logger.DEBUG);
    }

    if (commandLine.hasOption("h")) {
        // Show help
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("PowerFolder", COMMAND_LINE_OPTIONS);
        return;
    }

    int rconPort = Integer.valueOf(ConfigurationEntry.NET_RCON_PORT.getDefaultValue());
    String portStr = commandLine.getOptionValue("k");
    if (StringUtils.isNotBlank(portStr)) {
        try {
            rconPort = Integer.valueOf(portStr.trim());
        } catch (Exception e) {
            log.warning("Unable to parse rcon port: " + portStr + ". " + e);
        }
    }

    boolean runningInstanceFound = RemoteCommandManager.hasRunningInstance(rconPort);

    if (commandLine.hasOption("k")) {
        if (runningInstanceFound) {
            System.out.println("Stopping " + NAME);
            // Send quit command
            RemoteCommandManager.sendCommand(rconPort, RemoteCommandManager.QUIT);
        } else {
            System.err.println("Process not running");
        }

        // stop
        return;
    }

    // set language from commandline to preferences
    if (commandLine.hasOption("g")) {
        Preferences.userNodeForPackage(Translation.class).put("locale", commandLine.getOptionValue("g"));
    }

    if (JavaVersion.systemVersion().isOpenJDK()) {
        Object[] options = { "Open Oracle home page and exit", "Exit" };

        int n = JOptionPane.showOptionDialog(null,
                "You are using OpenJDK which is unsupported.\n"
                        + "Please install the client with bundled JRE or install the Oracle JRE",
                "Unsupported JRE", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options,
                options[0]);

        if (n == 0) {
            try {
                BrowserLauncher.openURL("http://www.java.com");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        return;
    }

    // The controller.
    Controller controller = Controller.createController();

    String[] files = commandLine.getArgs();
    // Parsing of command line completed

    boolean commandContainsRemoteCommands = files != null && files.length >= 1 || commandLine.hasOption("e")
            || commandLine.hasOption("r") || commandLine.hasOption("a");
    // Try to start controller
    boolean startController = !commandContainsRemoteCommands || !runningInstanceFound;
    try {
        log.info("PowerFolder v" + Controller.PROGRAM_VERSION);

        // Start controller
        if (startController) {
            controller.startConfig(commandLine);
        }

        // Send remote command if there a files in commandline
        if (files != null && files.length > 0) {
            // Parse filenames and build remote command
            StringBuilder openFilesRCommand = new StringBuilder(RemoteCommandManager.OPEN);

            for (String file : files) {
                openFilesRCommand.append(file);
                // FIXME: Add ; separator ?
            }

            // Send remote command to running PowerFolder instance
            RemoteCommandManager.sendCommand(openFilesRCommand.toString());
        }

        if (commandLine.hasOption("e")) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.MAKEFOLDER + commandLine.getOptionValue("e"));
        }
        if (commandLine.hasOption("r")) {
            RemoteCommandManager
                    .sendCommand(RemoteCommandManager.REMOVEFOLDER + commandLine.getOptionValue("r"));
        }
        if (commandLine.hasOption("a")) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.COPYLINK + commandLine.getOptionValue("a"));
        }
    } catch (Throwable t) {
        t.printStackTrace();
        log.log(Level.SEVERE, "Throwable", t);
        return;
    }

    // Begin monitoring memory usage.
    if (controller.isStarted() && controller.isUIEnabled()) {
        ScheduledExecutorService service = controller.getThreadPool();
        service.scheduleAtFixedRate(new MemoryMonitor(controller), 1, 1, TimeUnit.MINUTES);
    }

    // Not go into console mode if ui is open
    if (!startController) {
        if (runningInstanceFound) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.SHOW_UI);
        }
        return;
    }

    System.out.println("------------ " + NAME + " " + Controller.PROGRAM_VERSION + " started ------------");

    boolean restartRequested = false;
    do {
        // Go into restart loop
        while (controller.isStarted() || controller.isShuttingDown()) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                log.log(Level.WARNING, "InterruptedException", e);
                return;
            }
        }

        restartRequested = controller.isRestartRequested();
        if (restartRequested) {
            Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
            for (Thread thread : threads.keySet()) {
                if (thread.getName().startsWith("PoolThread") || thread.getName().startsWith("Reconnector")
                        || thread.getName().startsWith("ConHandler")) {
                    thread.interrupt();
                }
            }
            log.info("Restarting controller");
            System.out.println(
                    "------------ " + NAME + " " + Controller.PROGRAM_VERSION + " restarting ------------");
            controller = null;
            System.gc();
            controller = Controller.createController();
            // Start controller
            controller.startConfig(commandLine);
        }
    } while (restartRequested);
}