Example usage for javax.swing ProgressMonitorInputStream getProgressMonitor

List of usage examples for javax.swing ProgressMonitorInputStream getProgressMonitor

Introduction

In this page you can find the example usage for javax.swing ProgressMonitorInputStream getProgressMonitor.

Prototype

public ProgressMonitor getProgressMonitor() 

Source Link

Document

Get the ProgressMonitor object being used by this stream.

Usage

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  .jav  a 2 s . c  om
                    }
                    //                  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:br.org.acessobrasil.silvinha.util.versoes.AtualizadorDeVersoes.java

public boolean baixarVersao() {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    NameValuePair param = new NameValuePair("param", "update");
    method.setRequestBody(new NameValuePair[] { param });
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    JFrame down = new JFrame("Download");
    File downFile = null;/*from   w  w  w. j  a v  a 2  s  .c o m*/
    InputStream is = null;
    FileOutputStream fos = null;
    try {
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            log.error("Method failed: " + method.getStatusLine());
        }
        Header header = method.getResponseHeader("Content-Disposition");
        String fileName = "silvinha.exe";
        if (header != null) {
            fileName = header.getValue().split("=")[1];
        }
        // Read the response body.
        is = method.getResponseBodyAsStream();
        down.pack();
        ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(down,
                TradAtualizadorDeVersoes.FAZ_DOWNLOAD_FILE + fileName, is);
        pmis.getProgressMonitor().setMinimum(0);
        pmis.getProgressMonitor().setMaximum((int) method.getResponseContentLength());
        downFile = new File(fileName);
        fos = new FileOutputStream(downFile);
        int c;
        while (((c = pmis.read()) != -1) && (!pmis.getProgressMonitor().isCanceled())) {
            fos.write(c);
        }
        fos.flush();
        fos.close();
        String msgOK = TradAtualizadorDeVersoes.DOWNLOAD_EXITO
                + TradAtualizadorDeVersoes.DESEJA_ATUALIZAR_EXECUTAR + TradAtualizadorDeVersoes.ARQUIVO_DE_NOME
                + fileName + TradAtualizadorDeVersoes.LOCALIZADO_NA + TradAtualizadorDeVersoes.PASTA_INSTALACAO
                + TradAtualizadorDeVersoes.APLICACAO_DEVE_SER_ENCERRADA
                + TradAtualizadorDeVersoes.DESEJA_CONTINUAR_ATUALIZACAO;
        if (JOptionPane.showConfirmDialog(null, msgOK, TradAtualizadorDeVersoes.ATUALIZACAO_DO_PROGRAMA,
                JOptionPane.YES_NO_OPTION) == 0) {
            return true;
        } else {
            return false;
        }
    } catch (HttpException he) {
        log.error("Fatal protocol violation: " + he.getMessage(), he);
        return false;
    } catch (InterruptedIOException iioe) {
        method.abort();
        String msg = GERAL.OP_CANCELADA_USUARIO + TradAtualizadorDeVersoes.DIRECIONADO_A_APLICACAO;
        JOptionPane.showMessageDialog(down, msg);
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException ioe) {
            method.releaseConnection();
            System.exit(0);
        }
        if (downFile != null && downFile.exists()) {
            downFile.delete();
        }
        return false;
        //         System.err.println("Fatal transport error: " + iioe.getMessage());
        //         iioe.printStackTrace();
    } catch (IOException ioe) {
        log.error("Fatal transport error: " + ioe.getMessage(), ioe);
        return false;
    } finally {
        //Release the connection.
        method.releaseConnection();
    }
}

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

/**
 * Get the ressource from the webdav server.
 *
 * @param uri the uri to the ressource./* ww  w  . java2 s. co 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 = 0;
    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:gov.nih.nci.nbia.StandaloneDMDispatcher.java

private void downloadInstaller(String downloadUrl) {
    String fileName = getInstallerName(downloadUrl);
    InputStream in;/*from www  . ja  v  a2s.com*/

    // 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:com.docdoku.client.data.MainModel.java

private void downloadFile(Component pParent, File pLocalFile, int contentLength, InputStream inputStream)
        throws IOException {
    System.out.println("Downloading file");
    ProgressMonitorInputStream in = null;
    OutputStream out = null;/*from   ww w.j  av  a2  s  .  c  om*/
    try {
        out = new BufferedOutputStream(new FileOutputStream(pLocalFile), Config.BUFFER_CAPACITY);
        in = new ProgressMonitorInputStream(pParent, I18N.BUNDLE.getString("DownloadMsg_part1"),
                new BufferedInputStream(inputStream, Config.BUFFER_CAPACITY));
        ProgressMonitor pm = in.getProgressMonitor();
        pm.setMaximum(contentLength);
        byte[] data = new byte[Config.CHUNK_SIZE];
        int length;
        while ((length = in.read(data)) != -1) {
            out.write(data, 0, length);
        }

        out.flush();

    } finally {
        out.close();
        in.close();
    }
}

From source file:com.docdoku.client.data.MainModel.java

private void downloadFileWithServlet(Component pParent, File pLocalFile, String pURL) throws IOException {
    System.out.println("Downloading file from servlet");
    ProgressMonitorInputStream in = null;
    OutputStream out = null;/*from   w w  w .  jav  a  2s  .c o  m*/
    HttpURLConnection conn = null;
    try {
        //Hack for NTLM proxy
        //perform a head method to negociate the NTLM proxy authentication
        performHeadHTTPMethod(pURL);

        out = new BufferedOutputStream(new FileOutputStream(pLocalFile), Config.BUFFER_CAPACITY);
        URL url = new URL(pURL);
        conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestMethod("GET");
        byte[] encoded = org.apache.commons.codec.binary.Base64
                .encodeBase64((getLogin() + ":" + getPassword()).getBytes("ISO-8859-1"));
        conn.setRequestProperty("Authorization", "Basic " + new String(encoded, "US-ASCII"));
        conn.connect();
        int code = conn.getResponseCode();
        System.out.println("Download HTTP response code: " + code);
        in = new ProgressMonitorInputStream(pParent, I18N.BUNDLE.getString("DownloadMsg_part1"),
                new BufferedInputStream(conn.getInputStream(), Config.BUFFER_CAPACITY));
        ProgressMonitor pm = in.getProgressMonitor();
        pm.setMaximum(conn.getContentLength());
        byte[] data = new byte[Config.CHUNK_SIZE];
        int length;
        while ((length = in.read(data)) != -1) {
            out.write(data, 0, length);
        }
        out.flush();
    } finally {
        out.close();
        in.close();
        conn.disconnect();
    }
}

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

/**
 * Get the ressource from the webdav server.
 *
 * @param uri the uri to the ressource.//w w  w.  java2  s .  com
 * @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();
}