List of usage examples for java.io Closeable close
public void close() throws IOException;
From source file:CB_Utils.Util.Downloader.java
/** * Start downloading the remote resource. The target object should not be accessed until after calling waitUntilCompleted(). *///from w ww . ja v a2 s . c om @Override public void run() { synchronized (stateLock) { if (started) { return; } else { started = true; running = true; } } BufferedInputStream bis = null; BufferedOutputStream bos = null; BufferedReader br = null; try { /* open connection to the URL */ checkState(); progressString = "Opening connection to remote resource"; progressUpdated = true; final URLConnection link; try { link = url.openConnection(); link.connect(); } catch (Exception e) { progressString = "Failed to open connection to remote resource"; progressUpdated = true; throw e; } /* get length of the remote resource */ checkState(); progressString = "Getting length of remote resource"; progressUpdated = true; /* get size of webpage in bytes; -1 if unknown */ final int length = link.getContentLength(); synchronized (lengthLock) { totalLength = length; } progressUpdated = true; /* open input stream to remote resource */ checkState(); progressString = "Opening input stream to remote resource"; progressUpdated = true; InputStream input = null; try { if (totalLength < 1) { // load with http Request HttpGet httppost = new HttpGet(url.toString()); // Execute HTTP Post Request try { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, HttpUtils.conectionTimeout); HttpConnectionParams.setSoTimeout(httpParameters, HttpUtils.socketTimeout); DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); HttpResponse response = httpClient.execute(httppost); input = response.getEntity().getContent(); } catch (ConnectTimeoutException e1) { e1.printStackTrace(); } catch (ClientProtocolException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } else { input = link.getInputStream(); } if (target instanceof File) { bis = new BufferedInputStream(input); } else if (target instanceof StringBuilder) { final String contentType = link.getContentType().toLowerCase(Locale.ENGLISH); /* look for charset, if specified */ String charset = null; final Matcher m = Pattern.compile(".*charset[\\s]*=([^;]++).*").matcher(contentType); if (m.find()) { charset = m.group(1).trim(); } if ((charset != null) && charset.length() > 0) { try { br = new BufferedReader(new InputStreamReader(input, charset)); } catch (Exception e) { br = null; } } if (br == null) { br = new BufferedReader(new InputStreamReader(input)); } } } catch (Exception e) { progressString = "Failed to open input stream to remote resource"; progressUpdated = true; throw e; } /* open output stream, if necessary */ if (target instanceof File) { checkState(); progressString = "Opening output stream to local file"; progressUpdated = true; try { /* create parent directories, if necessary */ final File f = (File) target; final File parent = f.getParentFile(); if ((parent != null) && !parent.exists()) { parent.mkdirs(); } bos = new BufferedOutputStream(f.getFileOutputStream()); } catch (Exception e) { progressString = "Failed to open output stream to local file"; progressUpdated = true; throw e; } } /* download remote resource iteratively */ progressString = "Downloading"; progressUpdated = true; try { if (target instanceof File) { final byte[] byteBuffer = new byte[BUFFER_SIZE]; while (true) { checkState(); final int byteCount = bis.read(byteBuffer, 0, BUFFER_SIZE); /* check for end-of-stream */ if (byteCount == -1) { break; } bos.write(byteBuffer, 0, byteCount); synchronized (lengthLock) { downloadedLength += byteCount; } progressUpdated = true; } } else if (target instanceof StringBuilder) { final char[] charBuffer = new char[BUFFER_SIZE]; final StringBuilder sb = (StringBuilder) target; while (true) { checkState(); final int charCount = br.read(charBuffer, 0, BUFFER_SIZE); /* check for end-of-stream */ if (charCount == -1) { break; } sb.append(charBuffer, 0, charCount); synchronized (lengthLock) { downloadedLength += charCount; /* may be inaccurate because byte != char */ } progressUpdated = true; } } } catch (Exception e) { progressString = "Failed to download remote resource"; progressUpdated = true; throw e; } /* download completed successfully */ progressString = "Download completed"; progressUpdated = true; } catch (Exception e) { error = e; } finally { /* clean-up */ for (Closeable c : new Closeable[] { bis, br, bos }) { if (c != null) { try { c.close(); } catch (Exception e) { /* ignore */ } } } synchronized (stateLock) { running = false; completed = true; } } }
From source file:gov.nih.nci.ncicb.tcga.dcc.dam.dao.DAMQueriesLevel2.java
private void closeFile(final Closeable fileStream) { try {//from w w w . jav a2 s .com fileStream.close(); } catch (IOException ie) { logger.logToLogger(Level.ERROR, "Error closing file " + ie.getMessage()); } }
From source file:com.atomicleopard.thundr.ftp.commons.SocketClient.java
private void closeQuietly(Closeable close) { if (close != null) { try {/* w ww.jav a2 s . c om*/ close.close(); } catch (IOException e) { } } }
From source file:org.escidoc.browser.ui.tools.FilterButtonListener.java
private ByteArrayInputStream zip(final Set<ResourceModel> set) throws IOException, EscidocClientException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); Closeable res = out; try {/*from w w w . ja v a2s.com*/ final ZipOutputStream zout = new ZipOutputStream(out); res = zout; for (final ResourceModel resourceModel : set) { zout.putNextEntry(new ZipEntry(resourceModel.getId())); // TODO String asXmlString = repositories.findByType(resourceModel.getType()) .getAsXmlString(resourceModel.getId()); Utils.copy(new ByteArrayInputStream(asXmlString.getBytes("UTF-8")), zout); zout.closeEntry(); } } finally { res.close(); } return new ByteArrayInputStream(out.toByteArray()); }
From source file:org.apache.carbondata.core.statusmanager.SegmentUpdateStatusManager.java
/** * This method closes the streams/* w ww . j a va 2 s .c om*/ * * @param streams - streams to close. */ private void closeStreams(Closeable... streams) { // Added if to avoid NullPointerException in case one stream is being passed as null if (null != streams) { for (Closeable stream : streams) { if (null != stream) { try { stream.close(); } catch (IOException e) { LOG.error("Error while closing stream" + stream); } } } } }
From source file:org.urbanstew.soundcloudapi.SoundCloudAPI.java
private void closeQuietly(Closeable closeable) { try {// w ww .j a v a2 s.co m if (closeable != null) closeable.close(); } catch (Exception e) { System.err.println("Exception during Closeable close: " + e); } }
From source file:org.mitre.dsmiley.httpproxy.ProxyServlet.java
protected void closeQuietly(Closeable closeable) { try {/*from w w w .j a v a 2 s . co m*/ closeable.close(); } catch (IOException e) { System.out.println(e.getMessage()); } }
From source file:corner.payment.services.impl.processor.AlipayProcessor.java
@Override public boolean verifyNotify(String notifyId) { if (notifyId == null) { throw new IllegalArgumentException("The notifyId is null"); }// www . j av a 2s . co m String alipayNotifyURL = String.format("%s?partner=%s¬ify_id=%s", QUERY_URL, partner, notifyId); java.io.Closeable input = null; try { URL url = new URL(alipayNotifyURL); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoOutput(false); urlConnection.setConnectTimeout(30 * 1000); urlConnection.setReadTimeout(30 * 1000); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); input = in; String inputLine = in.readLine().toString(); urlConnection.disconnect(); if ("true".equalsIgnoreCase(inputLine)) { return true; } } catch (Exception e) { e.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { } } } return false; }
From source file:io.selendroid.server.model.DefaultSelendroidDriver.java
@Override @SuppressWarnings("deprecation") public byte[] takeScreenshot() { ViewHierarchyAnalyzer viewAnalyzer = ViewHierarchyAnalyzer.getDefaultInstance(); // TODO ddary review later, but with getRecentDecorView() it seems to work better // long drawingTime = 0; // View container = null; // for (View view : viewAnalyzer.getTopLevelViews()) { // if (view != null && view.isShown() && view.hasWindowFocus() // && view.getDrawingTime() > drawingTime) { // container = view; // drawingTime = view.getDrawingTime(); // }// w ww. j a v a2 s . c om // } // final View mainView = container; final View mainView = viewAnalyzer.getRecentDecorView(); if (mainView == null) { throw new SelendroidException("No open windows."); } done = false; long end = System.currentTimeMillis() + serverInstrumentation.getAndroidWait().getTimeoutInMillis(); final byte[][] rawPng = new byte[1][1]; ServerInstrumentation.getInstance().getCurrentActivity().runOnUiThread(new Runnable() { public void run() { synchronized (syncObject) { Display display = serverInstrumentation.getCurrentActivity().getWindowManager() .getDefaultDisplay(); Point size = new Point(); try { display.getSize(size); } catch (NoSuchMethodError ignore) { // Older than api level 13 size.x = display.getWidth(); size.y = display.getHeight(); } // Get root view View view = mainView.getRootView(); // Create the bitmap to use to draw the screenshot final Bitmap bitmap = Bitmap.createBitmap(size.x, size.y, Bitmap.Config.ARGB_8888); final Canvas canvas = new Canvas(bitmap); // Get current theme to know which background to use final Activity activity = serverInstrumentation.getCurrentActivity(); final Theme theme = activity.getTheme(); final TypedArray ta = theme .obtainStyledAttributes(new int[] { android.R.attr.windowBackground }); final int res = ta.getResourceId(0, 0); final Drawable background = activity.getResources().getDrawable(res); // Draw background background.draw(canvas); // Draw views view.draw(canvas); ByteArrayOutputStream stream = new ByteArrayOutputStream(); if (!bitmap.compress(Bitmap.CompressFormat.PNG, 70, stream)) { throw new RuntimeException("Error while compressing screenshot image."); } try { stream.flush(); stream.close(); } catch (IOException e) { throw new RuntimeException("I/O Error while capturing screenshot: " + e.getMessage()); } finally { Closeable closeable = (Closeable) stream; try { if (closeable != null) { closeable.close(); } } catch (IOException ioe) { // ignore } } rawPng[0] = stream.toByteArray(); mainView.destroyDrawingCache(); done = true; syncObject.notify(); } } }); waitForDone(end, serverInstrumentation.getAndroidWait().getTimeoutInMillis(), "Failed to take screenshot."); return rawPng[0]; }
From source file:hu.api.SivaPlayerVideoServlet.java
/** * Close closable resource./*from w ww. j a v a 2 s. c o m*/ * * @param resource * to close. */ private static void close(Closeable resource) { // Check if specified file is not null and try to close it if so if (resource != null) { try { resource.close(); } catch (IOException ignore) { // ignore } } }