Example usage for javax.swing ProgressMonitor setMillisToPopup

List of usage examples for javax.swing ProgressMonitor setMillisToPopup

Introduction

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

Prototype

public void setMillisToPopup(int millisToPopup) 

Source Link

Document

Specifies the amount of time it will take for the popup to appear.

Usage

From source file:hermes.store.schema.DefaultJDBCAdapter.java

private void executeStatements(Connection connection, String[] statements) throws SQLException {
    final StringBuffer message = new StringBuffer();
    ProgressMonitor progressMonitor = null;

    if (HermesBrowser.getBrowser() != null) {
        progressMonitor = new ProgressMonitor(HermesBrowser.getBrowser(), "Initialising message stores... ",
                "Connecting...", 0, statements.length);

        progressMonitor.setMillisToDecideToPopup(100);
        progressMonitor.setMillisToPopup(400);
    }//from  w w  w .  j  a v  a  2 s  . c om

    final QueryRunner runner = new QueryRunner();

    for (int i = 0; i < statements.length; i++) {
        try {
            log.debug("executing: " + statements[i]);

            if (progressMonitor != null) {
                progressMonitor.setProgress(statements.length);
                progressMonitor.setNote("Executing statement " + i + " of " + statements.length);
            }

            runner.update(connection, statements[i]);
        } catch (SQLException ex) {
            log.error(ex.getMessage());
        }
    }
}

From source file:gov.nih.nci.nbia.StandaloneDMDispatcher.java

private void downloadInstaller(String downloadUrl) {
    String fileName = getInstallerName(downloadUrl);
    InputStream in;/*from w  w  w  .  j  a v a  2 s .c  o m*/

    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            // here is the place to check client certs and throw an
            // exception if certs are wrong. When there is nothing all certs
            // accepted.
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // here is the place to check server certs and throw an
            // exception if certs are wrong. When there is nothing all certs
            // accepted.
        }
    } };
    // Install the all-trusting trust manager
    try {
        final SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                // Here is the palce to check host name against to
                // certificate owner
                return true;
            }
        };
        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } catch (KeyManagementException | NoSuchAlgorithmException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } finally {
    }

    try {
        URL url = new URL(downloadUrl);
        in = url.openStream();
        FileOutputStream fos = new FileOutputStream(new File(fileName));

        int length = -1;
        ProgressMonitorInputStream pmis;
        pmis = new ProgressMonitorInputStream(null,
                "Downloading new version of installer for NBIA Data Retriever...", in);

        ProgressMonitor monitor = pmis.getProgressMonitor();
        monitor.setMillisToPopup(0);
        monitor.setMinimum(0);
        monitor.setMaximum((int) 200000000); // The actual size is much
        // smaller,
        // but we have no way to
        // know
        // the actual size so picked
        // this big number

        byte[] buffer = new byte[1024];// buffer for portion of data from
        // connection

        while ((length = pmis.read(buffer)) > 0) {
            fos.write(buffer, 0, length);
        }
        pmis.close();
        fos.flush();
        fos.close();
        in.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:jshm.gui.GuiUtil.java

public static void openImageOrBrowser(final Frame owner, final String urlStr) {
    new SwingWorker<Void, Void>() {
        private BufferedImage image = null;
        private Throwable t = null;
        private boolean canceled = false;

        protected Void doInBackground() throws Exception {
            ProgressMonitor progress = null;

            try {
                // try to see if it's an image before downloading the
                // whole thing
                GetMethod method = new GetMethod(urlStr);
                Client.getHttpClient().executeMethod(method);
                Header h = method.getResponseHeader("Content-type");

                if (null != h && h.getValue().toLowerCase().startsWith("image/")) {
                    //                  jshm.util.TestTimer.start();
                    ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(owner, "Loading image...",
                            method.getResponseBodyAsStream());
                    progress = pmis.getProgressMonitor();
                    //                  System.out.println("BEFORE max: " + progress.getMaximum());
                    h = method.getResponseHeader("Content-length");

                    if (null != h) {
                        try {
                            progress.setMaximum(Integer.parseInt(h.getValue()));
                        } catch (NumberFormatException e) {
                        }//from ww w. ja  v a  2 s. com
                    }
                    //                  System.out.println("AFTER max: " + progress.getMaximum());

                    progress.setMillisToDecideToPopup(250);
                    progress.setMillisToPopup(1000);

                    image = javax.imageio.ImageIO.read(pmis);
                    pmis.close();
                    //                  jshm.util.TestTimer.stop();
                    //                  jshm.util.TestTimer.start();
                    image = GraphicsUtilities.toCompatibleImage(image);
                    //                  jshm.util.TestTimer.stop();
                }

                method.releaseConnection();
            } catch (OutOfMemoryError e) {
                LOG.log(Level.WARNING, "OutOfMemoryError trying to load image", e);
                image = null; // make it open in browser
            } catch (Throwable e) {
                if (null != progress && progress.isCanceled()) {
                    canceled = true;
                } else {
                    t = e;
                }
            }

            return null;
        }

        public void done() {
            if (canceled)
                return;

            if (null == image) {
                if (null == t) {
                    // no error, just the url wasn't an image, so launch the browser
                    Util.openURL(urlStr);
                } else {
                    LOG.log(Level.WARNING, "Error opening image URL", t);
                    ErrorInfo ei = new ErrorInfo("Error", "Error opening image URL", null, null, t, null, null);
                    JXErrorPane.showDialog(owner, ei);
                }
            } else {
                SpInfoViewer viewer = new SpInfoViewer();
                viewer.setTitle(urlStr);
                viewer.setImage(image, true);
                viewer.setLocationRelativeTo(owner);
                viewer.setVisible(true);
            }
        }
    }.execute();
}

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 www  .j  a  va2s.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 w w.  ja  v  a 2s  .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:oct.analysis.application.dat.OCTAnalysisManager.java

/**
 * This method will take care of interacting with the user in determining
 * where the fovea is within the OCT. It first lets the user inspect the
 * automatically identified locations where the fovea may be and then choose
 * the selection that is at the fovea. If none of the automated findings are
 * at the fovea the user has the option to manual specify it's location.
 * Finally, the chosen X coordinate (within the OCT) of the fovea is set in
 * the manager and can be obtained via the getFoveaCenterXPosition getter.
 *
 * @param fullAutoMode find the fovea automatically without user input when
 * true, otherwise find the fovea in semi-automatic mode involving user
 * interaction//from   ww w  .  j a  v a2  s .co  m
 */
public void findCenterOfFovea(boolean fullAutoMode) throws InterruptedException, ExecutionException {
    //disable clicking other components while processing by enabling glass pane
    JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(imgPanel);
    Component glassPane = topFrame.getGlassPane();
    glassPane.setVisible(true);

    //monitor progress of finding the fovea
    ProgressMonitor pm = new ProgressMonitor(imgPanel, "Analyzing OCT for fovea...", "", 0, 100);
    pm.setMillisToDecideToPopup(0);
    pm.setMillisToPopup(100);
    pm.setProgress(0);
    FoveaFindingTask fvtask = new FoveaFindingTask(!fullAutoMode, glassPane);
    fvtask.addPropertyChangeListener((PropertyChangeEvent evt) -> {
        if ("progress".equals(evt.getPropertyName())) {
            int progress1 = (Integer) evt.getNewValue();
            pm.setProgress(progress1);
        }
    });
    fvtask.execute();
}

From source file:org.ecoinformatics.seek.ecogrid.quicksearch.GetMetadataAction.java

/**
 * Invoked when an action occurs. It will transfer the original metadata
 * into a html file. The namespace will be the key to find stylesheet. If no
 * sytlesheet found, metadata will be null.
 * /* w w w. j  a va  2  s.  co m*/
 * @param e
 *            ActionEvent
 */
public void actionPerformed(ActionEvent e) {

    super.actionPerformed(e);
    NamedObj object = getTarget();
    if (object instanceof ResultRecord) {
        this.item = (ResultRecord) object;
    }

    if (item == null) {
        JOptionPane.showMessageDialog(null, "There is no metadata associated with this component.");
        return;
    }

    ProgressMonitor progressMonitor = new ProgressMonitor(null, "Acquiring Metadata ", "", 0, 5);
    progressMonitor.setMillisToDecideToPopup(100);
    progressMonitor.setMillisToPopup(10);
    progressMonitor.setProgress(0);
    this.metadataSource = item.getFullRecord();
    progressMonitor.setProgress(1);
    this.nameSpace = item.getNamespace();
    progressMonitor.setProgress(2);
    this.htmlFileName = item.getRecordId();
    //System.out.println("the html file name is ====== "+htmlFileName);
    progressMonitor.setProgress(3);

    if (configuration == null) {
        configuration = getConfiguration();
    }
    if (metadataSource != null && nameSpace != null && htmlFileName != null && configuration != null) {
        if (htmlFileName.endsWith(XMLFILEEXTENSION)) {
            htmlFileName = htmlFileName + HTMLFILEEXTENSION;
        }
        try {
            progressMonitor.setProgress(4);
            metadata = StaticUtil.getMetadataHTMLurl(metadataSource, nameSpace, htmlFileName);
            //System.out.println("before open html page");
            configuration.openModel(null, metadata, metadata.toExternalForm());
            progressMonitor.setProgress(5);
            //System.out.println("after open html page");
            progressMonitor.close();
        } catch (Exception ee) {
            log.debug("The error to get metadata html ", ee);
        }

    }
}

From source file:org.madeirahs.editor.ui.SubviewUI.java

/**
 * Constructs a new Submissions viewing UI. It is recommended that you call
 * this from the UI thread./*from  w ww  . j  av  a2 s.com*/
 * 
 * @param owner
 * @param prov
 */
public SubviewUI(MainUI owner, final FTPProvider prov) {
    super(owner, "Database Submissions");
    parent = owner;
    this.prov = prov;
    final SubviewUI inst = this;
    list = new JList();
    list.setBorder(new EmptyBorder(5, 5, 5, 5));
    btns = new JPanel();
    ((FlowLayout) btns.getLayout()).setAlignment(FlowLayout.RIGHT);
    load = new JButton("Load");
    load.addActionListener(new LoadListener());
    accept = new JButton("Accept");
    accept.addActionListener(new AcceptListener());
    remove = new JButton("Remove");
    remove.addActionListener(new RemoveListener());
    btns.add(load);
    btns.add(accept);
    btns.add(remove);
    add(BorderLayout.CENTER, list);
    add(BorderLayout.SOUTH, btns);
    setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    addWindowListener(new OnCloseDialog());
    setSize(300, 300);
    setLocationRelativeTo(parent);
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                ProgressMonitor prog = new ProgressMonitor(inst, "Retrieving Database", "", 0, 101);
                prog.setMillisToDecideToPopup(0);
                prog.setMillisToPopup(0);
                dbi = Database.getInstance(ServerFTP.dbDir, prov, prog);
                prog.close();

                try {
                    loadListData();
                } catch (IllegalServerStateException e) {
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(null,
                            "Server communication error.  Please contact server admin.\n" + e.toString(),
                            "Bad Response", JOptionPane.ERROR_MESSAGE);
                }

                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        list.validate();
                    }

                });
            } catch (ClassCastException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(parent, "Error downloading database:\n" + e.toString(),
                        "I/O Error", JOptionPane.ERROR_MESSAGE);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

    }).start();
}

From source file:org.silverpeas.openoffice.windows.webdav.WebdavManager.java

/**
 * Get the ressource from the webdav server.
 *
 * @param uri the uri to the ressource.//from  w  ww  .j a  va  2  s  .  c  o  m
 * @param lockToken the current lock token.
 * @return the path to the saved file on the filesystem.
 * @throws IOException
 */
public String getFile(URI uri, String lockToken) throws IOException {
    GetMethod method = executeGetFile(uri);
    String fileName = uri.getPath();
    fileName = fileName.substring(fileName.lastIndexOf('/') + 1);
    fileName = URLDecoder.decode(fileName, "UTF-8");
    UIManager.put("ProgressMonitor.progressText", MessageUtil.getMessage("download.file.title"));
    ProgressMonitorInputStream is = new ProgressMonitorInputStream(null,
            MessageUtil.getMessage("downloading.remote.file") + ' ' + fileName,
            new BufferedInputStream(method.getResponseBodyAsStream()));
    fileName = fileName.replace(' ', '_');
    ProgressMonitor monitor = is.getProgressMonitor();
    monitor.setMaximum(new Long(method.getResponseContentLength()).intValue());
    monitor.setMillisToDecideToPopup(0);
    monitor.setMillisToPopup(0);
    File tempDir = new File(System.getProperty("java.io.tmpdir"), "silver-" + System.currentTimeMillis());
    tempDir.mkdirs();
    File tmpFile = new File(tempDir, fileName);
    FileOutputStream fos = new FileOutputStream(tmpFile);
    byte[] data = new byte[64];
    int c;
    try {
        while ((c = is.read(data)) > -1) {
            fos.write(data, 0, c);
        }
    } catch (InterruptedIOException ioinex) {
        logger.log(Level.INFO, "{0} {1}",
                new Object[] { MessageUtil.getMessage("info.user.cancel"), ioinex.getMessage() });
        unlockFile(uri, lockToken);
        System.exit(0);
    } finally {
        fos.close();
    }
    return tmpFile.getAbsolutePath();
}

From source file:richtercloud.document.scanner.gui.MainPanel.java

/**
 *
 * @param images images to be transformed into a {@link OCRSelectPanelPanel}
 * or {@code null} indicating that no scan data was persisted when opening a
 * persisted entry//from  w w  w  . ja v a 2 s  .c om
 * @param documentFile The {@link File} the document is stored in.
 * {@code null} indicates that the document has not been saved yet (e.g. if
 * the {@link OCRSelectComponent} represents scan data).
 * @throws DocumentAddException
 */
public void addDocument(final List<BufferedImage> images, final File documentFile, final Object entityToEdit)
        throws DocumentAddException {
    if (ADD_DOCUMENT_ASYNC) {
        final ProgressMonitor progressMonitor = new ProgressMonitor(this, //parent
                "Generating new document tab", //message
                null, //note
                0, //min
                100 //max
        );
        progressMonitor.setMillisToPopup(0);
        progressMonitor.setMillisToDecideToPopup(0);
        final SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
            private OCRSelectComponent createdOCRSelectComponentScrollPane;

            @Override
            protected Void doInBackground() throws Exception {
                try {
                    this.createdOCRSelectComponentScrollPane = addDocumentRoutine(images, documentFile,
                            entityToEdit, progressMonitor);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                return null;
            }

            @Override
            protected void done() {
                progressMonitor.close();
                addDocumentDone(this.createdOCRSelectComponentScrollPane);
            }
        };
        worker.execute();
        progressMonitor.setProgress(1); //ProgressMonitor dialog blocks until SwingWorker.done
        //is invoked
    } else {
        OCRSelectComponent oCRSelectComponentScrollPane = addDocumentRoutine(images, documentFile, entityToEdit,
                null //progressMonitor
        );
        addDocumentDone(oCRSelectComponentScrollPane);
    }
}