Example usage for javax.swing ProgressMonitorInputStream ProgressMonitorInputStream

List of usage examples for javax.swing ProgressMonitorInputStream ProgressMonitorInputStream

Introduction

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

Prototype

public ProgressMonitorInputStream(Component parentComponent, Object message, InputStream in) 

Source Link

Document

Constructs an object to monitor the progress of an input 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) {
                        }//  w  w  w  .  j av  a2 s  .co  m
                    }
                    //                  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:org.jahia.loganalyzer.internal.JahiaLogAnalyzerImpl.java

private Reader getFileReader(java.awt.Component uiComponent, File file, MonitorInputStream.Monitor monitor)
        throws FileNotFoundException {
    if (uiComponent != null) {
        InputStream in = new BufferedInputStream(
                new ProgressMonitorInputStream(uiComponent, "Reading " + file, new FileInputStream(file)));
        return new InputStreamReader(in);
    } else {/*from w w w .  j av  a2s .c om*/
        return new InputStreamReader(new MonitorInputStream(monitor, new FileInputStream(file)));
    }
}

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

private void downloadInstaller(String downloadUrl) {
    String fileName = getInstallerName(downloadUrl);
    InputStream in;//from   w  ww .j  a  v  a 2s . 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:com.docdoku.client.actions.MainController.java

private void uploadFileWithServlet(final Component pParent, File pLocalFile, String pURL) throws IOException {
    System.out.println("Uploading file with servlet");
    InputStream in = null;/*from  w  w w  .java2  s  . co  m*/
    OutputStream out = null;
    HttpURLConnection conn = null;
    try {
        //Hack for NTLM proxy
        //perform a head method to negociate the NTLM proxy authentication
        performHeadHTTPMethod(pURL);

        MainModel model = MainModel.getInstance();
        URL url = new URL(pURL);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        byte[] encoded = org.apache.commons.codec.binary.Base64
                .encodeBase64((model.getLogin() + ":" + model.getPassword()).getBytes("ISO-8859-1"));
        conn.setRequestProperty("Authorization", "Basic " + new String(encoded, "US-ASCII"));

        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "--------------------" + Long.toString(System.currentTimeMillis(), 16);
        byte[] header = (twoHyphens + boundary + lineEnd + "Content-Disposition: form-data; name=\"upload\";"
                + " filename=\"" + pLocalFile + "\"" + lineEnd + lineEnd).getBytes("ISO-8859-1");
        byte[] footer = (lineEnd + twoHyphens + boundary + twoHyphens + lineEnd).getBytes("ISO-8859-1");

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        //conn.setRequestProperty("Content-Length",len + "");
        long len = header.length + pLocalFile.length() + footer.length;
        conn.setFixedLengthStreamingMode((int) len);
        out = new BufferedOutputStream(conn.getOutputStream(), Config.BUFFER_CAPACITY);
        out.write(header);

        byte[] data = new byte[Config.CHUNK_SIZE];
        int length;
        in = new ProgressMonitorInputStream(pParent,
                I18N.BUNDLE.getString("UploadMsg_part1") + " " + pLocalFile.getName() + " ("
                        + (int) (pLocalFile.length() / 1024) + I18N.BUNDLE.getString("UploadMsg_part2"),
                new BufferedInputStream(new FileInputStream(pLocalFile), Config.BUFFER_CAPACITY));
        while ((length = in.read(data)) != -1) {
            out.write(data, 0, length);
        }

        out.write(footer);
        out.flush();

        int code = conn.getResponseCode();
        System.out.println("Upload HTTP response code: " + code);
        if (code != 200) {
            //TODO create a more suitable exception
            throw new IOException();
        }
        out.close();
    } catch (InterruptedIOException pEx) {
        throw pEx;
    } catch (IOException pEx) {
        out.close();
        throw pEx;
    } finally {
        in.close();
        conn.disconnect();
    }
}

From source file:com.zigabyte.stock.stratplot.StrategyPlotter.java

/** Load stock data specified in file field.  If the data is from a
    serialized file, uses a ProgressMonitorInputStream to show
    progress.  Once data is loaded, sets compareHistory to first
    symbol in COMPARE_INDEX_SYMBOLS found in data, and sets
    begin/end dates to the begin/end dates of this symbol, or
    of the first history in the data if no compare symbol was found.
    Shows a dialog when either completed or an error occurs.
**//*from   w ww .j a v a  2s. c  o m*/
protected void loadFile() {
    try {
        // get file
        String filePath = this.fileField.getText().trim();
        if (filePath.length() == 0)
            throw new IllegalArgumentException("Empty file");
        File file = new File(filePath);

        // choose parser
        StockMarketHistoryFactory parser;
        {
            String fileFormat = (String) this.fileFormatCombo.getSelectedItem();
            if ("Metastock".equals(fileFormat))
                parser = new MetastockParser(true);
            else if ("Serialized".equals(fileFormat))
                parser = new SerializedStockFilesParser(false);
            else if ("SerializedGZ".equals(fileFormat))
                parser = new SerializedStockFilesParser(true);
            else
                throw new IllegalArgumentException("Unrecognized file format: " + fileFormat);
        }
        // load data using parser
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                runButton.setEnabled(false);
                viewDataButton.setEnabled(false);
            }
        });
        this.histories = null; // allow gc
        this.loadedHistoriesFile = null;
        if (!(parser instanceof SerializedStockFilesParser)) {
            this.histories = parser.loadHistory(file);
        } else {
            // use ProgressMonitorInputStream
            SerializedStockFilesParser serializedParser = (SerializedStockFilesParser) parser;
            InputStream in = new FileInputStream(file);
            ProgressMonitorInputStream pmIn = new ProgressMonitorInputStream(this, file.getName(), in);
            this.histories = serializedParser.loadHistory(pmIn);
            pmIn.close();
        }
        this.loadedHistoriesFile = file;
        if (histories.size() > 0) {

            // initialize compareSymbol
            String compareIndexSymbol = "";
            for (String spSymbol : COMPARE_INDEX_SYMBOLS) {
                if (histories.get(spSymbol) != null) {
                    compareIndexSymbol = spSymbol;
                    break;
                }
            }
            this.compareIndexSymbolField.setText(compareIndexSymbol);

            // initialize start/end fields
            StockHistory sampleHistory = (compareIndexSymbol.length() > 0 ? histories.get(compareIndexSymbol)
                    : histories.get(0));
            if (sampleHistory.size() > 0) {
                this.startDateField.setValue(sampleHistory.get(0).getDate());
                this.endDateField.setValue(sampleHistory.get(sampleHistory.size() - 1).getDate());
            }
        }
        // display completed dialog
        String msg = "Loaded " + this.histories.size() + " histories";
        JOptionPane.showMessageDialog(this, msg, "Load complete", JOptionPane.INFORMATION_MESSAGE);
    } catch (FileNotFoundException e) {
        showErrorDialog(e, false);
    } catch (Exception e) {
        showErrorDialog(e);
    } finally {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                runButton.setEnabled(histories != null);
                viewDataButton.setEnabled(histories != null);
                loadFileButton.setCursor(null); // clear wait cursor
            }
        });
    }
}

From source file:com.pironet.tda.TDA.java

private void loadSession(File file, boolean isRecent) throws IOException {
    final ObjectInputStream ois = new ObjectInputStream(new ProgressMonitorInputStream(this,
            "Opening session " + file, new GZIPInputStream(new FileInputStream(file))));

    setFileOpen(true);/* w w w  .j a va  2 s.  com*/
    firstFile = false;
    resetMainPanel();
    initDumpDisplay(null);

    final SwingWorker worker = new SwingWorker() {

        @SuppressWarnings("unchecked")
        public Object construct() {
            synchronized (syncObject) {
                try {
                    dumpFile = (String) ois.readObject();
                    topNodes = (Vector<DefaultMutableTreeNode>) ois.readObject();
                    dumpStore = (DumpStore) ois.readObject();
                    ois.close();
                } catch (IOException | ClassNotFoundException ex) {
                    ex.printStackTrace();
                } finally {
                    try {
                        ois.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
                createTree();
            }

            return null;
        }
    };
    worker.start();
    if (!isRecent) {
        PrefManager.get().addToRecentSessions(file.getAbsolutePath());
    }
}

From source file:com.pironet.tda.TDA.java

private void addDumpStream(InputStream inputStream, String file, boolean withLogfile) {
    final InputStream parseFileStream = new ProgressMonitorInputStream(this, "Parsing " + file, inputStream);

    //Create the nodes.
    if (!runningAsJConsolePlugin || topNodes.size() == 0) {
        topNodes.add(new DefaultMutableTreeNode(new Logfile(file)));
    }// w w w  .  j a  va  2  s  .  c o m
    final DefaultMutableTreeNode top = topNodes.get(topNodes.size() - 1);

    if ((!withLogfile && logFile == null) || isLogfileSizeOk(file)) {
        logFile = new DefaultMutableTreeNode(new LogFileContent(file));
        if (!runningAsVisualVMPlugin) {
            top.add(logFile);
        }
    }
    setFileOpen(true);

    final SwingWorker worker = new SwingWorker() {

        public Object construct() {
            synchronized (syncObject) {
                int divider = topSplitPane.getDividerLocation();
                addThreadDumps(top, parseFileStream);
                createTree();
                tree.expandRow(1);

                topSplitPane.setDividerLocation(divider);
            }

            return null;
        }
    };
    worker.start();
}

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   ww  w. j a  v 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: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  w w w.  j a  va  2s .  co m
    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.pironet.tda.TDA.java

/**
 * open and parse loggc file/*from  www .  j a va2  s  .  c  o m*/
 */
private void openLoggcFile() {
    int returnVal = fc.showOpenDialog(this.getRootPane());

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        final String loggcFile = file.getAbsolutePath();
        try {
            final InputStream loggcFileStream = new ProgressMonitorInputStream(this, "Parsing " + loggcFile,
                    new FileInputStream(loggcFile));

            final SwingWorker worker = new SwingWorker() {
                public Object construct() {
                    try {
                        DefaultMutableTreeNode top = fetchTop(tree.getSelectionPath());

                        ((Logfile) top.getUserObject()).getUsedParser().parseLoggcFile(loggcFileStream, top);

                        addThreadDumps(top, loggcFileStream);
                        createTree();
                        getRootPane().revalidate();
                        displayContent(null);
                    } finally {
                        try {
                            loggcFileStream.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                    return null;
                }
            };
            worker.start();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
    }
}