Example usage for javax.swing ProgressMonitor setProgress

List of usage examples for javax.swing ProgressMonitor setProgress

Introduction

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

Prototype

@SuppressWarnings("deprecation")
public void setProgress(int nv) 

Source Link

Document

Indicate the progress of the operation being monitored.

Usage

From source file:de.cismet.cids.custom.objecteditors.wunda_blau.WebDavPicturePanel.java

/**
 * DOCUMENT ME!/*  w w  w.j  a  va 2  s .com*/
 *
 * @param   fileName  DOCUMENT ME!
 *
 * @return  DOCUMENT ME!
 *
 * @throws  Exception  DOCUMENT ME!
 */
private BufferedImage downloadImageFromWebDAV(final String fileName) throws Exception {
    final InputStream iStream = webdavHelper.getFileFromWebDAV(fileName, webdavDirectory,
            getConnectionContext());
    try {
        final ImageInputStream iiStream = ImageIO.createImageInputStream(iStream);
        final Iterator<ImageReader> itReader = ImageIO.getImageReaders(iiStream);
        if (itReader.hasNext()) {
            final ImageReader reader = itReader.next();
            final ProgressMonitor monitor = new ProgressMonitor(this, "Bild wird bertragen...", "", 0, 100);
            //            monitor.setMillisToPopup(500);
            reader.addIIOReadProgressListener(new IIOReadProgressListener() {

                @Override
                public void sequenceStarted(final ImageReader source, final int minIndex) {
                }

                @Override
                public void sequenceComplete(final ImageReader source) {
                }

                @Override
                public void imageStarted(final ImageReader source, final int imageIndex) {
                    monitor.setProgress(monitor.getMinimum());
                }

                @Override
                public void imageProgress(final ImageReader source, final float percentageDone) {
                    if (monitor.isCanceled()) {
                        try {
                            iiStream.close();
                        } catch (final IOException ex) {
                            // NOP
                        }
                    } else {
                        monitor.setProgress(Math.round(percentageDone));
                    }
                }

                @Override
                public void imageComplete(final ImageReader source) {
                    monitor.setProgress(monitor.getMaximum());
                }

                @Override
                public void thumbnailStarted(final ImageReader source, final int imageIndex,
                        final int thumbnailIndex) {
                }

                @Override
                public void thumbnailProgress(final ImageReader source, final float percentageDone) {
                }

                @Override
                public void thumbnailComplete(final ImageReader source) {
                }

                @Override
                public void readAborted(final ImageReader source) {
                    monitor.close();
                }
            });

            final ImageReadParam param = reader.getDefaultReadParam();
            reader.setInput(iiStream, true, true);
            final BufferedImage result;
            try {
                result = reader.read(0, param);
            } finally {
                reader.dispose();
                iiStream.close();
            }
            return result;
        } else {
            return null;
        }
    } finally {
        IOUtils.closeQuietly(iStream);
    }
}

From source file:com.diversityarrays.kdxplore.trialmgr.trait.TraitExplorerPanel.java

private void doImportTraitsFileImpl(File file) {
    Context context = KDSmartApplication.getInstance();
    final ProgressMonitor monitor = new ProgressMonitor(TraitExplorerPanel.this, "Loading", "", 0, 100);
    ProgressReporter progressReporter = new ProgressReporter() {

        @Override/*from  ww  w .ja  va  2 s .  c o m*/
        public void setProgressNote(String note) {
            monitor.setNote(note);
        }

        @Override
        public void setProgressMaximum(int max) {
            monitor.setMaximum(max);
        }

        @Override
        public void setProgressCount(int count) {
            monitor.setProgress(count);
        }

        @Override
        public void dismissProgress() {
            monitor.close();
        }
    };

    try {
        Either<ImportError, TraitImportTransactions> either = offlineData.getKdxploreDatabase()
                .getKDXploreKSmartDatabase().importTraitsFile(context, file, progressReporter);

        if (either.isLeft()) {
            ImportError ie = either.left();
            MsgBox.error(TraitExplorerPanel.this, ie.getMessage("Import Traits"), "Import Failed");
        } else {
            TraitImportTransactions tit = either.right();

            if (!tit.traitsToBeUpdated.isEmpty()) {

            }

            refreshTraitsTable();

            StringBuilder sb = new StringBuilder("Import Result");
            if (tit.nSkipped > 0) {
                sb.append("\nSkipped ").append(tit.nSkipped);
            }
            if (!tit.traitsToBeAdded.isEmpty()) {
                sb.append("\nAdded: ").append(tit.traitsToBeAdded.size());
            }
            if (!tit.traitsToBeUpdated.isEmpty()) {
                sb.append("\nUpdated: ").append(tit.traitsToBeUpdated.size());
            }
            MsgBox.info(TraitExplorerPanel.this, sb.toString(), "Import Complete");
        }
    } finally {
        progressReporter.dismissProgress();
    }
}

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

public boolean LoadImage(String filename) {
    // where to save temp output file?
    final String sourceFile = filename;
    final String destinationFile = GetTempDestinationFile();

    LoadImageConverters();/*from w  ww  .  j a v a  2 s . c  o  m*/
    if (ChooseImageConversionOptions(false) == false)
        return false;

    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>() {
        @Override
        public Void doInBackground() {
            // read in image
            BufferedImage img;
            try {
                Log("<font color='green'>" + translator.get("Converting") + " " + destinationFile
                        + "</font>\n");
                // convert with style
                img = ImageIO.read(new File(sourceFile));
                int style = GetDrawStyle();
                Filter f = image_converters.get(style);
                TabToLog();
                f.SetParent(this);
                f.SetProgressMonitor(pm);
                f.SetDestinationFile(destinationFile);
                f.Convert(img);
                TabToDraw();
                previewPane.ZoomToFitPaper();
            } catch (IOException e) {
                Log("<font color='red'>" + translator.get("Failed") + e.getLocalizedMessage() + "</font>\n");
                recentFiles.remove(sourceFile);
                updateMenuBar();
            }

            pm.setProgress(100);
            return null;
        }

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

    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: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. ja va  2 s  . com*/

    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.usfirst.frc.team2084.neuralnetwork.HeadingNeuralNetworkTrainer.java

private void trainNetwork() {
    if (!training) {

        // Set training flag and disable button
        training = true;//from ww  w  . j a v a 2 s.com
        trainButton.setEnabled(false);

        final ProgressMonitor progressMonitor = new ProgressMonitor(frame, "Training Network...", "", 0, 100);
        progressMonitor.setMillisToDecideToPopup(100);
        progressMonitor.setMillisToPopup(400);

        @SuppressWarnings("unchecked")
        final ArrayList<XYDataItem> data = new ArrayList<>(outputGraphDataSeries.getItems());

        final int maxProgress = iterations * data.size();

        final SwingWorker<Void, Void> trainingWorker = new SwingWorker<Void, Void>() {

            @Override
            protected Void doInBackground() throws Exception {
                // Reset the neural network to default values
                synchronized (this) {
                    network.reset();
                    network.setEta(eta);
                    network.setMomentum(momentum);
                }

                outer: for (int j = 0; j < iterations; j++) {
                    for (int i = 0; i < data.size(); i++) {
                        if (!isCancelled()) {
                            XYDataItem d = data.get(i);
                            double error = convertAngleToInput(d.getXValue());
                            double output = d.getYValue();
                            synchronized (this) {
                                network.feedForward(error);
                                network.backPropagation(output);
                            }
                            int jl = j;
                            int il = i;
                            int progress = (int) (((float) (data.size() * jl + il + 1) / maxProgress) * 100);
                            setProgress(progress);
                        } else {
                            break outer;
                        }
                    }
                }

                displayNetwork();
                return null;
            }

            @Override
            protected void done() {
                training = false;
                trainButton.setEnabled(true);
                progressMonitor.close();
            }
        };
        trainingWorker.addPropertyChangeListener(new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("progress")) {
                    progressMonitor.setProgress((int) evt.getNewValue());
                }
                if (progressMonitor.isCanceled()) {
                    trainingWorker.cancel(true);
                }
            }
        });
        trainingWorker.execute();
    }
}

From source file:jamel.gui.JamelWindow.java

/**
 * Exports a rapport.//from   w  w w . j a  va 2 s  .  co m
 */
public void exportRapport() {
    final int max = tabbedPane.getTabCount();
    final ProgressMonitor progressMonitor = new ProgressMonitor(this, "Exporting", "", 0, max);
    progressMonitor.setMillisToDecideToPopup(0);
    final String rc = System.getProperty("line.separator");
    final File outputDirectory = new File("exports/" + this.getTitle() + "-" + (new Date()).getTime());
    outputDirectory.mkdir();
    try {
        final FileWriter writer = new FileWriter(new File(outputDirectory, "Rapport.html"));
        writer.write("<HTML>" + rc);
        writer.write("<HEAD>");
        writer.write("<TITLE>" + this.getTitle() + "</TITLE>" + rc);
        writer.write("</HEAD>" + rc);
        writer.write("<BODY>" + rc);
        writer.write("<H1>" + this.getTitle() + "</H1>" + rc);
        writer.write("<HR>" + rc);
        final Date start = viewManager.getStart().getDate();
        final Date end = viewManager.getEnd().getDate();
        for (int tabIndex = 0; tabIndex < max; tabIndex++) {
            try {
                final JPanel currentTab = (JPanel) tabbedPane.getComponentAt(tabIndex);
                final String tabTitle = tabbedPane.getTitleAt(tabIndex);
                writer.write("<H2>" + tabTitle + "</H2>" + rc);
                writer.write("<TABLE>" + rc);
                final int chartPanelCount = currentTab.getComponentCount();
                for (int chartIndex = 0; chartIndex < chartPanelCount; chartIndex++) {
                    if ((chartIndex == 3) | (chartIndex == 6))
                        writer.write("<TR>" + rc);
                    final ChartPanel aChartPanel = (ChartPanel) currentTab.getComponent(chartIndex);
                    final JamelChart chart = (JamelChart) aChartPanel.getChart();
                    if (chart != null) {
                        final String chartTitle = chart.getTitle().getText();
                        if (!chartTitle.equals("Empty")) {
                            try {
                                chart.setTitle("");
                                chart.setTimeRange(start, end);
                                String imageName = (tabTitle + "-" + chartIndex + "-" + chartTitle + ".png")
                                        .replace(" ", "_").replace("&", "and");
                                ChartUtilities.saveChartAsPNG(new File(outputDirectory, imageName), chart,
                                        aChartPanel.getWidth(), aChartPanel.getHeight());
                                writer.write("<TD><IMG src=\"" + imageName + "\" title=\"" + chartTitle + "\">"
                                        + rc);
                                chart.setTitle(chartTitle);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                writer.write("</TABLE>" + rc);
                writer.write("<HR>" + rc);
            } catch (ClassCastException e) {
            }
            progressMonitor.setProgress(tabIndex);
        }
        writer.write("<H2>Scenario</H2>" + rc);
        writer.write(this.consoleText.toString());
        writer.write("</BODY>" + rc);
        writer.write("</HTML>" + rc);
        writer.close();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    progressMonitor.close();
}

From source file:ca.sqlpower.architect.swingui.SwingUIProjectLoader.java

/**
 * Saves this project by writing an XML description of it to a temp file, then renaming.
 * The location of the file is determined by this project's <code>file</code> property.
 *
 * @param pm An optional progress monitor which will be initialised then updated
 * periodically during the save operation.  If you use a progress monitor, don't
 * invoke this method on the AWT event dispatch thread!
 *//*from w  ww  .jav a 2 s  .c o m*/
public void save(ProgressMonitor pm) throws IOException, SQLObjectException {
    // write to temp file and then rename (this preserves old project file
    // when there's problems)
    if (file.exists() && !file.canWrite()) {
        // write problems with architect file will muck up the save process
        throw new SQLObjectException(
                Messages.getString("SwingUIProject.errorSavingProject", file.getAbsolutePath())); //$NON-NLS-1$
    }

    if (fileVersion != null && !fileVersion.equals(ArchitectVersion.APP_FULL_VERSION.toString())) {
        String message;
        try {
            ArchitectVersion oldFileVersion = new ArchitectVersion(fileVersion);
            if (oldFileVersion.compareTo(ArchitectVersion.APP_FULL_VERSION) < 0) {
                message = "Overwriting older file. Older versions may have problems "
                        + "loading the newer file format.";
            } else {
                message = "Overwriting newer file. Some data loss from loading may occur.";
            }
        } catch (Exception e) {
            message = "Overwriting file with an invalid version.";
        }
        UserPrompter prompter = getSession().createUserPrompter(message + "\nDo you wish to continue?",
                UserPromptType.BOOLEAN, UserPromptOptions.OK_CANCEL, UserPromptResponse.OK,
                UserPromptResponse.OK, "OK", "Cancel");
        UserPromptResponse response = prompter.promptUser();
        if (response.equals(UserPromptResponse.CANCEL)) {
            return;
        }
    }

    File backupFile = new File(file.getParent(), file.getName() + "~"); //$NON-NLS-1$

    // Several places we would check dir perms, but MS-Windows stupidly doesn't let use the
    // "directory write" attribute for directory writing (but instead overloads
    // it to mean 'this is a special directory'.

    File tempFile = null;
    tempFile = new File(file.getParent(), "tmp___" + file.getName()); //$NON-NLS-1$
    String encoding = "UTF-8"; //$NON-NLS-1$
    try {
        // If creating this temp file fails, feed the user back a more explanatory message
        out = new PrintWriter(tempFile, encoding);
    } catch (IOException e) {
        throw new SQLObjectException(Messages.getString("SwingUIProject.cannotCreateOutputFile") + e, e); //$NON-NLS-1$
    }

    progress = 0;
    this.pm = pm;
    if (pm != null) {
        int pmMax = 0;
        pm.setMinimum(0);
        if (getSession().isSavingEntireSource()) {
            pmMax = SQLObjectUtils
                    .countTablesSnapshot((SQLObject) getSession().getDBTree().getModel().getRoot());
        } else {
            pmMax = SQLObjectUtils.countTables((SQLObject) getSession().getDBTree().getModel().getRoot());
        }
        logger.debug("Setting progress monitor maximum to " + pmMax); //$NON-NLS-1$
        pm.setMaximum(pmMax);
        pm.setProgress(progress);
        pm.setMillisToDecideToPopup(0);
    }

    save(out, encoding); // Does ALL the actual I/O
    out = null;
    if (pm != null)
        pm.close();
    pm = null;

    // Do the rename dance.
    // This is a REALLY bad place for failure (especially if we've made the user wait several hours to save
    // a large project), so we MUST check failures from renameto (both places!)
    boolean fstatus = false;
    fstatus = backupFile.delete();
    logger.debug("deleting backup~ file: " + fstatus); //$NON-NLS-1$

    // If this is a brand new project, the old file does not yet exist, no point trying to rename it.
    // But if it already existed, renaming current to backup must succeed, or we give up.
    if (file.exists()) {
        fstatus = file.renameTo(backupFile);
        logger.debug("rename current file to backupFile: " + fstatus); //$NON-NLS-1$
        if (!fstatus) {
            throw new SQLObjectException((Messages.getString("SwingUIProject.couldNotRenameFile", //$NON-NLS-1$
                    tempFile.toString(), file.toString())));
        }
    }
    fstatus = tempFile.renameTo(file);
    if (!fstatus) {
        throw new SQLObjectException((Messages.getString("SwingUIProject.couldNotRenameTempFile", //$NON-NLS-1$
                tempFile.toString(), file.toString())));
    }
    logger.debug("rename tempFile to current file: " + fstatus); //$NON-NLS-1$
    fileVersion = ArchitectVersion.APP_FULL_VERSION.toString();
}

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

/**
 * Expand all the nodes in the tree representation of the model
 * //from ww  w .  j  av  a  2s . 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

/**
 * Load the provided file as an ontology replacing any assertions currently
 * in the assertions text area.//from   www  . j a  va  2s  .  co  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.monead.semantic.workbench.SemanticWorkbench.java

/**
 * Add the classes to the tree view/*from w  w w  .  ja v a 2  s .co m*/
 * 
 * @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();
        }
    }
}