List of usage examples for javax.swing ProgressMonitorInputStream close
public void close() throws IOException
FilterInputStream.close
to close the progress monitor as well as the stream. 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 w w w . ja va 2 s. c o 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: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. **//*www .j a va 2 s. com*/ 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:gov.nih.nci.nbia.StandaloneDMDispatcher.java
private void downloadInstaller(String downloadUrl) { String fileName = getInstallerName(downloadUrl); InputStream in;/*from w ww . j a v a2s .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.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;// ww w .jav a 2 s .c o 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.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 www .j a v a2s . 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(); } }