Example usage for javax.swing ProgressMonitor setNote

List of usage examples for javax.swing ProgressMonitor setNote

Introduction

In this page you can find the example usage for javax.swing ProgressMonitor setNote.

Prototype

public void setNote(String note) 

Source Link

Document

Specifies the additional note that is displayed along with the progress message.

Usage

From source file:com.monead.semantic.workbench.SemanticWorkbench.java

/**
 * Expand all the nodes in the tree representation of the model
 * /*from  w  w  w. ja  v  a 2  s. c o m*/
 * @return The final status to display
 */
private String expandAll() {
    int numNodes;
    ProgressMonitor progress;
    boolean canceled;
    final DefaultMutableTreeNode root = (DefaultMutableTreeNode) ontModelTree.getModel().getRoot();
    @SuppressWarnings("rawtypes")
    final Enumeration enumerateNodes = root.breadthFirstEnumeration();

    numNodes = 0;
    while (enumerateNodes.hasMoreElements()) {
        enumerateNodes.nextElement();
        ++numNodes;
    }

    LOGGER.debug("Expanding tree with row count: " + numNodes);

    progress = new ProgressMonitor(this, "Expanding Tree Nodes", "Starting node expansion", 0, numNodes);

    setStatus("Expanding all tree nodes");

    for (int row = 0; !progress.isCanceled() && row < numNodes; ++row) {
        progress.setProgress(row);
        if (row % 1000 == 0) {
            progress.setNote("Row " + row + " of " + numNodes);
        }

        ontModelTree.expandRow(row);
    }

    canceled = progress.isCanceled();

    progress.close();

    ontModelTree.scrollRowToVisible(0);

    if (!canceled) {
        // Select the tree view tab
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                tabbedPane.setSelectedIndex(TAB_NUMBER_TREE_VIEW);
            }
        });
    }

    return canceled ? "Tree node expansion canceled by user" : "Tree nodes expanded";
}

From source file:com.monead.semantic.workbench.SemanticWorkbench.java

/**
 * Add the classes to the tree view/*from  w  w  w . j a  v a2  s . com*/
 * 
 * @see #addIndividualsToTree(OntClass, DefaultMutableTreeNode,
 *      ProgressMonitor)
 * 
 * @param classesNode
 *          The classes parent node in the tree
 * @param maxIndividualsPerClass
 *          The maximum number of individuals to display in each class
 * @param messagePrefix
 *          Prefix for display messages
 */
private void addClassesToTree(DefaultMutableTreeNode classesNode, int maxIndividualsPerClass,
        String messagePrefix) {
    ProgressMonitor progress = null;
    DefaultMutableTreeNode oneClassNode;
    List<OntClass> ontClasses;
    ExtendedIterator<OntClass> classesIterator;
    int classNumber;
    try {
        classesIterator = ontModel.listClasses();

        setStatus(messagePrefix + "... obtaining the list of classes");

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("List of classes built");
        }
        ontClasses = new ArrayList<OntClass>();
        while (classesIterator.hasNext()) {
            ontClasses.add(classesIterator.next());
        }
        progress = new ProgressMonitor(this, "Create the model tree view", "Setting up the class list", 0,
                ontClasses.size());
        Collections.sort(ontClasses, new OntClassComparator());
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("List of classes sorted. Num classes:" + ontClasses.size());
        }

        classNumber = 0;
        for (OntClass ontClass : ontClasses) {
            setStatus(messagePrefix + " for class " + ontClass);

            if (MemoryWarningSystem.hasLatestAvailableTenuredGenAfterCollectionChanged(this)
                    && MemoryWarningSystem
                            .getLatestAvailableTenuredGenAfterCollection() < MINIMUM_BYTES_REQUIRED_FOR_TREE_BUILD) {
                throw new IllegalStateException(
                        "Insufficient memory available to complete building the tree (class iteration)");
            }

            if (progress.isCanceled()) {
                throw new RuntimeException("Tree model creation canceled by user");
            }

            progress.setNote(ontClass.toString());
            progress.setProgress(++classNumber);

            // Check whether class is to be skipped
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Check if class to be skipped: " + ontClass.getURI());
                for (String skipClass : classesToSkipInTree.keySet()) {
                    LOGGER.trace("Class to skip: " + skipClass + "  equal? "
                            + (skipClass.equals(ontClass.getURI())));
                }
            }
            if (filterEnableFilters.isSelected() && classesToSkipInTree.get(ontClass.getURI()) != null) {
                LOGGER.debug("Class to be skipped: " + ontClass.getURI());
                continue;
            }

            if (ontClass.isAnon()) {
                // Show anonymous classes based on configuration
                if (filterShowAnonymousNodes.isSelected()) {
                    oneClassNode = new DefaultMutableTreeNode(
                            new WrapperClass(ontClass.getId().getLabelString(), "[Anonymous class]", true));
                } else {
                    LOGGER.debug("Skip anonymous class: " + ontClass.getId().getLabelString());
                    continue;
                }
            } else {
                oneClassNode = new DefaultMutableTreeNode(new WrapperClass(ontClass.getLocalName(),
                        ontClass.getURI(), showFqnInTree.isSelected()));
                LOGGER.debug("Add class node: " + ontClass.getLocalName() + " (" + ontClass.getURI() + ")");
            }
            classesNode.add(oneClassNode);

            addIndividualsToTree(ontClass, oneClassNode, maxIndividualsPerClass, progress);
        }

    } finally {
        if (progress != null) {
            progress.close();
        }
    }
}

From source file:com.monead.semantic.workbench.SemanticWorkbench.java

/**
 * Load the provided file as an ontology replacing any assertions currently
 * in the assertions text area./* w  w  w  . j a  va2 s  . c o  m*/
 * 
 * @return The message to be presented on the status line
 */
private String loadOntologyFile() {
    final int chunkSize = 32000;
    StringBuilder allData;
    char[] chunk;
    long totalBytesRead = 0;
    int chunksRead = 0;
    int maxChunks;
    int bytesRead = -1;
    ProgressMonitor monitor = null;
    Reader reader = null;
    String message;
    boolean loadCanceled = false;

    if (rdfFileSource.isFile()) {
        lastDirectoryUsed = rdfFileSource.getBackingFile().getParentFile();
    }

    assertionsInput.setText("");
    invalidateModel(false);

    allData = new StringBuilder();
    chunk = new char[chunkSize];

    setStatus("Loading file " + rdfFileSource.getAbsolutePath());

    if (rdfFileSource.length() > 0 && rdfFileSource.length() < MAX_ASSERTION_BYTES_TO_LOAD_INTO_TEXT_AREA) {
        maxChunks = (int) (rdfFileSource.length() / chunkSize);
    } else {
        maxChunks = (int) (MAX_ASSERTION_BYTES_TO_LOAD_INTO_TEXT_AREA / chunkSize);
    }

    if (rdfFileSource.length() % chunkSize > 0) {
        ++maxChunks;
    }

    // Assume the file can be loaded
    hasIncompleteAssertionsInput = false;

    monitor = new ProgressMonitor(this, "Loading assertions from " + rdfFileSource.getName(), "0 bytes read", 0,
            maxChunks);

    try {
        reader = new InputStreamReader(rdfFileSource.getInputStream());
        while (!loadCanceled && (rdfFileSource.isUrl() || chunksRead < maxChunks)
                && (bytesRead = reader.read(chunk)) > -1) {
            totalBytesRead += bytesRead;

            chunksRead = (int) (totalBytesRead / chunk.length);

            if (chunksRead < maxChunks) {
                allData.append(chunk, 0, bytesRead);
            }

            if (chunksRead >= maxChunks) {
                monitor.setMaximum(chunksRead + 1);
            }

            monitor.setProgress(chunksRead);
            monitor.setNote("Read " + INTEGER_COMMA_FORMAT.format(totalBytesRead)
                    + (rdfFileSource.isFile() ? " of " + INTEGER_COMMA_FORMAT.format(rdfFileSource.length())
                            : " bytes")
                    + (chunksRead >= maxChunks ? " (Determining total file size)" : ""));

            loadCanceled = monitor.isCanceled();
        }

        if (!loadCanceled && rdfFileSource.isUrl()) {
            rdfFileSource.setLength(totalBytesRead);
        }

        if (!loadCanceled && rdfFileSource.length() > MAX_ASSERTION_BYTES_TO_LOAD_INTO_TEXT_AREA) {
            // The entire file was not loaded
            hasIncompleteAssertionsInput = true;
        }

        if (hasIncompleteAssertionsInput) {
            StringBuilder warningMessage;

            warningMessage = new StringBuilder();
            warningMessage.append("The file is too large to display. However the entire file will be loaded\n");
            warningMessage.append("into the model when it is built.\n\nDisplay size limit (bytes): ");
            warningMessage.append(INTEGER_COMMA_FORMAT.format(MAX_ASSERTION_BYTES_TO_LOAD_INTO_TEXT_AREA));
            if (rdfFileSource.isFile()) {
                warningMessage.append("\nFile size (bytes):");
                warningMessage.append(INTEGER_COMMA_FORMAT.format(rdfFileSource.length()));
            }
            warningMessage.append("\n\n");
            warningMessage.append("Note that the assersions text area will not permit editing\n");
            warningMessage.append("of the partially loaded file and the 'save assertions' menu\n");
            warningMessage.append("option will be disabled. These limitations are enabled\n");
            warningMessage.append("to prevent the accidental loss of information from the\n");
            warningMessage.append("source assertions file.");

            JOptionPane.showMessageDialog(this, warningMessage.toString(), "Max Display Size Reached",
                    JOptionPane.WARNING_MESSAGE);

            // Add text to the assertions text area to highlight the fact that the
            // entire file was not loaded into the text area
            allData.insert(0,
                    "# First " + INTEGER_COMMA_FORMAT.format(MAX_ASSERTION_BYTES_TO_LOAD_INTO_TEXT_AREA)
                            + " of " + INTEGER_COMMA_FORMAT.format(rdfFileSource.length())
                            + " bytes displayed\n\n");
            allData.insert(0, "# INCOMPLETE VERSION of the file: " + rdfFileSource.getAbsolutePath() + "\n");
            allData.append("\n\n# INCOMPLETE VERSION of the file: " + rdfFileSource.getAbsolutePath() + "\n");
            allData.append("# First " + INTEGER_COMMA_FORMAT.format(MAX_ASSERTION_BYTES_TO_LOAD_INTO_TEXT_AREA)
                    + " of " + INTEGER_COMMA_FORMAT.format(rdfFileSource.length()) + " bytes displayed\n");
        }

        // Set the loaded assertions into the text area, cleaning up Windows \r\n
        // endings, if found
        if (!loadCanceled) {
            assertionsInput.setText(allData.toString().replaceAll("\r\n", "\n"));
            assertionsInput.setSelectionEnd(0);
            assertionsInput.setSelectionStart(0);
            assertionsInput.moveCaretPosition(0);
            assertionsInput.scrollRectToVisible(new Rectangle(0, 0, 1, 1));

            message = "Loaded file" + (hasIncompleteAssertionsInput ? " (incomplete)" : "") + ": "
                    + rdfFileSource.getName();
            addRecentAssertedTriplesFile(rdfFileSource);

            // Select the assertions tab
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    tabbedPane.setSelectedIndex(TAB_NUMBER_ASSERTIONS);
                    setFocusOnCorrectTextArea();
                }
            });
        } else {
            message = "Assertions file load canceled by user";
        }
    } catch (Throwable throwable) {
        setStatus("Unable to load file: " + rdfFileSource.getName());
        JOptionPane.showMessageDialog(this, "Error: Unable to read file\n\n" + rdfFileSource.getAbsolutePath()
                + "\n\n" + throwable.getMessage(), "Error Reading File", JOptionPane.ERROR_MESSAGE);
        LOGGER.error("Unable to load the file: " + rdfFileSource.getAbsolutePath(), throwable);
        message = "Unable to load the file: " + rdfFileSource.getAbsolutePath();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Throwable throwable) {
                LOGGER.error("Unable to close input file", throwable);
            }
        }

        if (monitor != null) {
            monitor.close();
        }
    }

    return message;
}

From source file:com.marginallyclever.makelangelo.MainGUI.java

protected boolean LoadDXF(String filename) {
    if (ChooseImageConversionOptions(true) == false)
        return false;

    // where to save temp output file?
    final String destinationFile = GetTempDestinationFile();
    final String srcFile = filename;

    TabToLog();/*from w  ww .j  a va2  s.c  o m*/

    final ProgressMonitor pm = new ProgressMonitor(null, translator.get("Converting"), "", 0, 100);
    pm.setProgress(0);
    pm.setMillisToPopup(0);

    final SwingWorker<Void, Void> s = new SwingWorker<Void, Void>() {
        public boolean ok = false;

        @SuppressWarnings("unchecked")
        @Override
        public Void doInBackground() {
            Log("<font color='green'>" + translator.get("Converting") + " " + destinationFile + "</font>\n");

            Parser parser = ParserBuilder.createDefaultParser();

            double dxf_x2 = 0;
            double dxf_y2 = 0;
            OutputStreamWriter out = null;

            try {
                out = new OutputStreamWriter(new FileOutputStream(destinationFile), "UTF-8");
                DrawingTool tool = machineConfiguration.GetCurrentTool();
                out.write(machineConfiguration.GetConfigLine() + ";\n");
                out.write(machineConfiguration.GetBobbinLine() + ";\n");
                out.write("G00 G90;\n");
                tool.WriteChangeTo(out);
                tool.WriteOff(out);

                parser.parse(srcFile, DXFParser.DEFAULT_ENCODING);
                DXFDocument doc = parser.getDocument();
                Bounds b = doc.getBounds();
                double width = b.getMaximumX() - b.getMinimumX();
                double height = b.getMaximumY() - b.getMinimumY();
                double cx = (b.getMaximumX() + b.getMinimumX()) / 2.0f;
                double cy = (b.getMaximumY() + b.getMinimumY()) / 2.0f;
                double sy = machineConfiguration.GetPaperHeight() * 10 / height;
                double sx = machineConfiguration.GetPaperWidth() * 10 / width;
                double scale = (sx < sy ? sx : sy) * machineConfiguration.paper_margin;
                sx = scale * (machineConfiguration.reverseForGlass ? -1 : 1);
                // count all entities in all layers
                Iterator<DXFLayer> layer_iter = (Iterator<DXFLayer>) doc.getDXFLayerIterator();
                int entity_total = 0;
                int entity_count = 0;
                while (layer_iter.hasNext()) {
                    DXFLayer layer = (DXFLayer) layer_iter.next();
                    Log("<font color='yellow'>Found layer " + layer.getName() + "</font>\n");
                    Iterator<String> entity_iter = (Iterator<String>) layer.getDXFEntityTypeIterator();
                    while (entity_iter.hasNext()) {
                        String entity_type = (String) entity_iter.next();
                        List<DXFEntity> entity_list = (List<DXFEntity>) layer.getDXFEntities(entity_type);
                        Log("<font color='yellow'>+ Found " + entity_list.size() + " of type " + entity_type
                                + "</font>\n");
                        entity_total += entity_list.size();
                    }
                }
                // set the progress meter
                pm.setMinimum(0);
                pm.setMaximum(entity_total);

                // convert each entity
                layer_iter = doc.getDXFLayerIterator();
                while (layer_iter.hasNext()) {
                    DXFLayer layer = (DXFLayer) layer_iter.next();

                    Iterator<String> entity_type_iter = (Iterator<String>) layer.getDXFEntityTypeIterator();
                    while (entity_type_iter.hasNext()) {
                        String entity_type = (String) entity_type_iter.next();
                        List<DXFEntity> entity_list = layer.getDXFEntities(entity_type);

                        if (entity_type.equals(DXFConstants.ENTITY_TYPE_LINE)) {
                            for (int i = 0; i < entity_list.size(); ++i) {
                                pm.setProgress(entity_count++);
                                DXFLine entity = (DXFLine) entity_list.get(i);
                                Point start = entity.getStartPoint();
                                Point end = entity.getEndPoint();

                                double x = (start.getX() - cx) * sx;
                                double y = (start.getY() - cy) * sy;
                                double x2 = (end.getX() - cx) * sx;
                                double y2 = (end.getY() - cy) * sy;

                                // is it worth drawing this line?
                                double dx = x2 - x;
                                double dy = y2 - y;
                                if (dx * dx + dy * dy < tool.GetDiameter() / 2.0) {
                                    continue;
                                }

                                dx = dxf_x2 - x;
                                dy = dxf_y2 - y;

                                if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) {
                                    if (tool.DrawIsOn()) {
                                        tool.WriteOff(out);
                                    }
                                    tool.WriteMoveTo(out, (float) x, (float) y);
                                }
                                if (tool.DrawIsOff()) {
                                    tool.WriteOn(out);
                                }
                                tool.WriteMoveTo(out, (float) x2, (float) y2);
                                dxf_x2 = x2;
                                dxf_y2 = y2;
                            }
                        } else if (entity_type.equals(DXFConstants.ENTITY_TYPE_SPLINE)) {
                            for (int i = 0; i < entity_list.size(); ++i) {
                                pm.setProgress(entity_count++);
                                DXFSpline entity = (DXFSpline) entity_list.get(i);
                                entity.setLineWeight(30);
                                DXFPolyline polyLine = DXFSplineConverter.toDXFPolyline(entity);
                                boolean first = true;
                                for (int j = 0; j < polyLine.getVertexCount(); ++j) {
                                    DXFVertex v = polyLine.getVertex(j);
                                    double x = (v.getX() - cx) * sx;
                                    double y = (v.getY() - cy) * sy;
                                    double dx = dxf_x2 - x;
                                    double dy = dxf_y2 - y;

                                    if (first == true) {
                                        first = false;
                                        if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) {
                                            // line does not start at last tool location, lift and move.
                                            if (tool.DrawIsOn()) {
                                                tool.WriteOff(out);
                                            }
                                            tool.WriteMoveTo(out, (float) x, (float) y);
                                        }
                                        // else line starts right here, do nothing.
                                    } else {
                                        // not the first point, draw.
                                        if (tool.DrawIsOff())
                                            tool.WriteOn(out);
                                        if (j < polyLine.getVertexCount() - 1
                                                && dx * dx + dy * dy < tool.GetDiameter() / 2.0)
                                            continue; // less than 1mm movement?  Skip it. 
                                        tool.WriteMoveTo(out, (float) x, (float) y);
                                    }
                                    dxf_x2 = x;
                                    dxf_y2 = y;
                                }
                            }
                        } else if (entity_type.equals(DXFConstants.ENTITY_TYPE_POLYLINE)) {
                            for (int i = 0; i < entity_list.size(); ++i) {
                                pm.setProgress(entity_count++);
                                DXFPolyline entity = (DXFPolyline) entity_list.get(i);
                                boolean first = true;
                                for (int j = 0; j < entity.getVertexCount(); ++j) {
                                    DXFVertex v = entity.getVertex(j);
                                    double x = (v.getX() - cx) * sx;
                                    double y = (v.getY() - cy) * sy;
                                    double dx = dxf_x2 - x;
                                    double dy = dxf_y2 - y;

                                    if (first == true) {
                                        first = false;
                                        if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) {
                                            // line does not start at last tool location, lift and move.
                                            if (tool.DrawIsOn()) {
                                                tool.WriteOff(out);
                                            }
                                            tool.WriteMoveTo(out, (float) x, (float) y);
                                        }
                                        // else line starts right here, do nothing.
                                    } else {
                                        // not the first point, draw.
                                        if (tool.DrawIsOff())
                                            tool.WriteOn(out);
                                        if (j < entity.getVertexCount() - 1
                                                && dx * dx + dy * dy < tool.GetDiameter() / 2.0)
                                            continue; // less than 1mm movement?  Skip it. 
                                        tool.WriteMoveTo(out, (float) x, (float) y);
                                    }
                                    dxf_x2 = x;
                                    dxf_y2 = y;
                                }
                            }
                        }
                    }
                }

                // entities finished.  Close up file.
                tool.WriteOff(out);
                tool.WriteMoveTo(out, 0, 0);

                ok = true;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    if (out != null)
                        out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            pm.setProgress(100);
            return null;
        }

        @Override
        public void done() {
            pm.close();
            Log("<font color='green'>" + translator.get("Finished") + "</font>\n");
            PlayConversionFinishedSound();
            if (ok) {
                LoadGCode(destinationFile);
                TabToDraw();
            }
            Halt();
        }
    };

    s.addPropertyChangeListener(new PropertyChangeListener() {
        // Invoked when task's progress property changes.
        public void propertyChange(PropertyChangeEvent evt) {
            if ("progress" == evt.getPropertyName()) {
                int progress = (Integer) evt.getNewValue();
                pm.setProgress(progress);
                String message = String.format("%d%%\n", progress);
                pm.setNote(message);
                if (s.isDone()) {
                    Log("<font color='green'>" + translator.get("Finished") + "</font>\n");
                } else if (s.isCancelled() || pm.isCanceled()) {
                    if (pm.isCanceled()) {
                        s.cancel(true);
                    }
                    Log("<font color='green'>" + translator.get("Cancelled") + "</font>\n");
                }
            }
        }
    });

    s.execute();

    return true;
}

From source file:org.mbari.aved.ui.classifier.knowledgebase.SearchableConceptTreePanel.java

/**
 * Perfroms the database lookup of all matching Concepts.
 * @param text/*from  ww  w . ja va2 s. c o  m*/
 * @param useGlobSearch
 */
private void loadNodes(final String text, final boolean useGlobSearch) {
    Collection matches = null;

    try {
        if (useGlobSearch) {
            if (!cachedGlobSearches.contains(text)) {
                matches = LWConceptNameDAO.getInstance().findNamesBySubString(text);
                cachedGlobSearches.add(text);
                cachedWordSearches.add(text);
            }
        } else {
            if (!cachedWordSearches.contains(text)) {
                matches = LWConceptNameDAO.getInstance().findNamesStartingWith(text);
                cachedWordSearches.add(text);
            }
        }
    } catch (DAOException e) {
        if (log.isErrorEnabled()) {
            log.error("Database lookup of " + text + " failed", e);
        }
    }

    /*
     * If we loaded the matched names from the database then we need
     * to open the Concept such that it gets cached under the root
     * concept.
     */
    if (matches != null) {
        final ProgressMonitor progressMonitor = new ProgressMonitor(AppFrameDispatcher.getFrame(),
                "Loading search results for '" + text + "'", "", 0, matches.size());
        int n = 0;

        for (Iterator i = matches.iterator(); i.hasNext();) {
            n++;

            final IConceptName cn = (IConceptName) i.next();

            progressMonitor.setProgress(n);
            progressMonitor.setNote("Loading '" + cn.getName() + "'");

            /*
             * Have to open the node in a seperate thread for the
             * progress monitor to update. Here we're using foxtrot.
             */
            Worker.post(new Job() {
                public Object run() {
                    openNode((Concept) cn.getConcept());

                    return null;
                }
            });
        }

        progressMonitor.close();
    }
}

From source file:pt.lsts.neptus.plugins.bathym.XyzExporter.java

@Override
public String process(IMraLogGroup source, ProgressMonitor pmonitor) {
    pmonitor.setMaximum(100);/*from   ww  w  .  j  a  v  a2s.  c om*/
    PluginUtils.editPluginProperties(this, true);
    this.pmonitor = pmonitor;
    this.pmonitor.setMillisToDecideToPopup(0);

    this.pmonitor.setProgress(0);

    finder = TidePredictionFactory.create(source);
    if (finder == null)
        tideCorrection = false;

    try {
        writer = new BufferedWriter(new FileWriter(file));

        // Writing header
        writer.write(COMMENT_STRING + "XYZ Data" + LINE_ENDING);
        double startTimeSeconds = source.getLsfIndex().getStartTime();
        writer.write(COMMENT_STRING + "Date of data: "
                + DateTimeUtil.dateFormatterUTC.format(new Date((long) (startTimeSeconds * 1E3)))
                + LINE_ENDING);
        writer.write(COMMENT_STRING + "Tide corrected: "
                + (tideCorrection ? "yes (" + finder.getName() + ")" : "no") + LINE_ENDING);

        // Data source info
        String dataSource = "";
        if (exportEstimatedState)
            dataSource = "navigation";
        if (exportMultibeam)
            dataSource += (dataSource.isEmpty() ? "" : ", ") + "multibeam";
        if (exportDistance)
            dataSource += (dataSource.isEmpty() ? "" : ", ") + "dvl";
        writer.write(COMMENT_STRING + "Data source: " + dataSource + LINE_ENDING);
        writer.write(COMMENT_STRING + LINE_ENDING);

        writer.write(COMMENT_STRING + "Longitude, Latitude, Depth" + LINE_ENDING);
        writer.write(COMMENT_STRING + "(decimal degrees, decimal degrees, meters)" + LINE_ENDING);
    } catch (Exception e) {
        e.printStackTrace();
        return I18n.textf("%name while trying to write to file: %message.", e.getClass().getSimpleName(),
                e.getMessage());
    }

    this.pmonitor.setProgress(10);

    if (exportEstimatedState) {
        pmonitor.setNote(I18n.text("Processing EstimatedState data"));
        processEstimatedStates(source);
    }

    this.pmonitor.setProgress(30);
    if (exportMultibeam) {
        pmonitor.setNote(I18n.text("Processing Multibeam data"));
        processMultibeam(source);
    }

    this.pmonitor.setProgress(60);
    if (exportDistance) {
        pmonitor.setNote(I18n.text("Processing DVL data"));
        processDvl(source);
    }

    this.pmonitor.setProgress(80);
    try {
        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    String outputPath = file.getName();
    if (compressOutput) {
        this.pmonitor.setProgress(90);
        pmonitor.setNote(I18n.text("Compressing output"));
        ZipUtils.zipDir(file.getAbsolutePath() + ".zip", file.getAbsolutePath());
        outputPath += ".zip";
        pmonitor.setNote("Deleting file");
        FileUtils.deleteQuietly(file);
    }

    this.pmonitor.setProgress(100);

    return I18n.textf("File written to %file.", outputPath);
}

From source file:us.daveread.basicquery.BasicQuery.java

/**
 * Executes all the queries//w  w w. ja v a2 s. c o  m
 */
private void runAllQueries() {
    int numExecutions, numQueries;
    int execution, query;
    ProgressMonitor monitor;
    boolean canceled;
    java.util.Date start;
    int elapsed;
    long remaining;
    int hours, minutes, seconds;

    numQueries = querySelection.getModel().getSize();
    try {
        numExecutions = Integer
                .parseInt(JOptionPane.showInputDialog(this, Resources.getString("dlgAllQueriesText"),
                        Resources.getString("dlgAllQueriesTitle"), JOptionPane.QUESTION_MESSAGE));
    } catch (Exception any) {
        numExecutions = 0;
    }

    messageOut(Resources.getString("msgNumExecutions", numExecutions + ""));

    monitor = new ProgressMonitor(this, Resources.getString("dlgRunAllQueriesProgressTitle"),
            Resources.getString("dlgRunAllQueriesProgressNote", "0", numExecutions + "", "0", numQueries + ""),
            0, numQueries * Math.abs(numExecutions));

    getContentPane().setCursor(new Cursor(Cursor.WAIT_CURSOR));

    if (numExecutions < 0) {
        numExecutions = Math.abs(numExecutions);

        for (query = 0; !monitor.isCanceled() && query < numQueries; ++query) {
            querySelection.setSelectedIndex(query);
            elapsed = -1;
            for (execution = 0; !monitor.isCanceled() && execution < numExecutions; ++execution) {
                monitor.setProgress(query * numExecutions + execution);
                if (elapsed <= 0) {
                    monitor.setNote(Resources.getString("dlgRunAllQueriesProgressNote", (execution + 1) + "",
                            numExecutions + "", (query + 1) + "", numQueries + ""));
                } else {
                    remaining = elapsed
                            * ((numExecutions * (numQueries - (query + 1))) + (numExecutions - execution));
                    hours = (int) (remaining / SECONDS_PER_HOUR);
                    remaining -= hours * SECONDS_PER_HOUR;
                    minutes = (int) (remaining / SECONDS_PER_MINUTE);
                    remaining -= minutes * SECONDS_PER_MINUTE;
                    seconds = (int) remaining;

                    monitor.setNote(Resources.getString("dlgRunAllQueriesProgressNoteWithRemainTime",
                            (execution + 1) + "", numExecutions + "", (query + 1) + "", numQueries + "",
                            Utility.formattedNumber(hours, "00"), Utility.formattedNumber(minutes, "00"),
                            Utility.formattedNumber(seconds, "00")));
                }
                messageOut(Resources.getString("dlgRunAllQueriesProgressNote", (execution + 1) + "",
                        numExecutions + "", (query + 1) + "", numQueries + ""));
                start = new java.util.Date();
                processStatement(true);
                elapsed = (int) ((new java.util.Date().getTime() - start.getTime()) / 1000);
            }
        }
    } else {
        elapsed = -1;
        for (execution = 0; !monitor.isCanceled() && execution < numExecutions; ++execution) {
            start = new java.util.Date();
            for (query = 0; !monitor.isCanceled() && query < numQueries; ++query) {
                querySelection.setSelectedIndex(query);
                monitor.setProgress(execution * numQueries + query);

                if (elapsed <= 0) {
                    monitor.setNote(Resources.getString("dlgRunAllQueriesProgressNote", (execution + 1) + "",
                            numExecutions + "", (query + 1) + "", numQueries + ""));
                } else {
                    remaining = elapsed * (numExecutions - execution);
                    hours = (int) (remaining / SECONDS_PER_HOUR);
                    remaining -= hours * SECONDS_PER_HOUR;
                    minutes = (int) (remaining / SECONDS_PER_MINUTE);
                    remaining -= minutes * SECONDS_PER_MINUTE;
                    seconds = (int) remaining;

                    monitor.setNote(Resources.getString("dlgRunAllQueriesProgressNoteWithRemainTime",
                            (execution + 1) + "", numExecutions + "", (query + 1) + "", numQueries + "",
                            Utility.formattedNumber(hours, "00"), Utility.formattedNumber(minutes, "00"),
                            Utility.formattedNumber(seconds, "00")));
                }

                messageOut(Resources.getString("dlgRunAllQueriesProgressNote", (execution + 1) + "",
                        numExecutions + "", (query + 1) + "", numQueries + ""));
                processStatement(true);
            }
            elapsed = (int) ((new java.util.Date().getTime() - start.getTime()) / 1000);
        }
    }

    canceled = monitor.isCanceled();

    monitor.close();

    getContentPane().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

    if (canceled) {
        userMessage(Resources.getString("dlgExecutionsCanceledText"),
                Resources.getString("dlgExecutionsCanceledTitle"), JOptionPane.WARNING_MESSAGE);
    } else if (numExecutions != 0) {
        userMessage(Resources.getString("dlgExecutionsCompletedText"),
                Resources.getString("dlgExecutionsCompletedTitle"), JOptionPane.INFORMATION_MESSAGE);
    } else {
        userMessage(Resources.getString("dlgExecutionsNoneText"), Resources.getString("dlgExecutionsNoneTitle"),
                JOptionPane.INFORMATION_MESSAGE);
    }
}