List of usage examples for java.io ByteArrayOutputStream flush
public void flush() throws IOException
From source file:net.solarnetwork.node.util.ClassUtils.java
/** * Load a classpath SQL resource into a String. * // w w w . j a va 2s .c o m * @param resourceName * the SQL resource to load * @param clazz * the Class to load the resource from * @return the String */ public static String getResourceAsString(String resourceName, Class<?> clazz) { InputStream in = clazz.getResourceAsStream(resourceName); if (in == null) { throw new RuntimeException("Resource [" + resourceName + "] not found"); } ByteArrayOutputStream out = new ByteArrayOutputStream(); try { byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } out.flush(); return out.toString(); } catch (IOException e) { throw new RuntimeException("Error reading resource [" + resourceName + ']', e); } finally { try { in.close(); } catch (IOException ex) { LOG.warn("Could not close InputStream", ex); } try { out.close(); } catch (IOException ex) { LOG.warn("Could not close OutputStream", ex); } } }
From source file:Main.java
public static byte[] read(InputStream stream) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try {/*from w w w . j a v a 2 s . c o m*/ byte[] buffer = new byte[1024]; int length; while ((length = stream.read(buffer)) >= 0) { byteArrayOutputStream.write(buffer, 0, length); } stream.close(); return byteArrayOutputStream.toByteArray(); } finally { byteArrayOutputStream.flush(); byteArrayOutputStream.close(); } }
From source file:com.kcs.core.utilities.Utility.java
public static byte[] generateToBytes(Object jaxbElement) throws Exception { ByteArrayOutputStream output = new ByteArrayOutputStream(); generate(jaxbElement, output);//from w w w .j av a 2 s. co m output.flush(); output.close(); return output.toByteArray(); }
From source file:com.qhn.bhne.xhmusic.utils.MyUtils.java
public static byte[] getBytes(InputStream is) throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0;/* w ww .j av a 2 s . c om*/ while ((len = is.read(buffer)) != -1) { bos.write(buffer, 0, len); } is.close(); bos.flush(); byte[] result = bos.toByteArray(); System.out.println(new String(result)); return result; }
From source file:Main.java
public static Bitmap loadImageFromUrl(String url) { ByteArrayOutputStream out = null; Bitmap bitmap = null;//from w w w. j av a 2s . c om int BUFFER_SIZE = 1024 * 8; try { BufferedInputStream in = new BufferedInputStream(new URL(url).openStream(), BUFFER_SIZE); out = new ByteArrayOutputStream(BUFFER_SIZE); int length = 0; byte[] tem = new byte[BUFFER_SIZE]; length = in.read(tem); while (length != -1) { out.write(tem, 0, length); out.flush(); length = in.read(tem); } in.close(); if (out.toByteArray().length != 0) { bitmap = BitmapFactory.decodeByteArray(out.toByteArray(), 0, out.size()); } else { out.close(); return null; } out.close(); } catch (OutOfMemoryError e) { out.reset(); BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inSampleSize = 2; opts.inJustDecodeBounds = false; bitmap = BitmapFactory.decodeByteArray(out.toByteArray(), 0, out.size(), opts); return bitmap; } catch (Exception e) { return bitmap; } return bitmap; }
From source file:com.truebanana.http.HTTPResponse.java
protected static HTTPResponse from(HTTPRequest request, HttpURLConnection connection, InputStream content) { HTTPResponse response = new HTTPResponse(); response.originalRequest = request;//from w w w . j av a 2s . com if (content != null) { try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] data = new byte[16384]; int nRead; while ((nRead = content.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); response.content = buffer.toByteArray(); } catch (IOException e) { e.printStackTrace(); } } try { response.statusCode = connection.getResponseCode(); } catch (IOException e) { } String message = null; try { message = connection.getResponseMessage(); } catch (IOException e) { message = e.getLocalizedMessage(); } response.responseMessage = response.statusCode + (message != null ? " " + message : ""); response.headers = connection.getHeaderFields(); response.requestURL = connection.getURL().toString(); return response; }
From source file:net.solarnetwork.util.ClassUtils.java
/** * Load a classpath SQL resource into a String. * //w ww. j ava 2 s.c o m * @param resourceName the SQL resource to load * @param clazz the Class to load the resource from * @return the String */ public static String getResourceAsString(String resourceName, Class<?> clazz) { InputStream in = clazz.getResourceAsStream(resourceName); if (in == null) { throw new RuntimeException("Fesource [" + resourceName + "] not found"); } ByteArrayOutputStream out = new ByteArrayOutputStream(); try { byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } out.flush(); return out.toString(); } catch (IOException e) { throw new RuntimeException("Error reading resource [" + resourceName + ']', e); } finally { try { in.close(); } catch (IOException ex) { LOG.warn("Could not close InputStream", ex); } try { out.close(); } catch (IOException ex) { LOG.warn("Could not close OutputStream", ex); } } }
From source file:com.evolveum.midpoint.report.impl.ReportNodeUtils.java
public static InputStream executeOperation(String host, String fileName, String intraClusterHttpUrlPattern, String operation) throws CommunicationException, SecurityViolationException, ObjectNotFoundException, ConfigurationException, IOException { fileName = fileName.replaceAll("\\s", SPACE); InputStream inputStream = null; InputStream entityContent = null; LOGGER.trace("About to initiate connection with {}", host); try {/* ww w. j a va 2s . c om*/ if (StringUtils.isNotEmpty(intraClusterHttpUrlPattern)) { LOGGER.trace("The cluster uri pattern: {} ", intraClusterHttpUrlPattern); URI requestUri = buildURI(intraClusterHttpUrlPattern, host, fileName); fileName = URLDecoder.decode(fileName, ReportTypeUtil.URLENCODING); LOGGER.debug("Sending request to the following uri: {} ", requestUri); HttpRequestBase httpRequest = buildHttpRequest(operation); httpRequest.setURI(requestUri); httpRequest.setHeader("User-Agent", ReportTypeUtil.HEADER_USERAGENT); HttpClient client = HttpClientBuilder.create().build(); try (CloseableHttpResponse response = (CloseableHttpResponse) client.execute(httpRequest)) { HttpEntity entity = response.getEntity(); Integer statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { LOGGER.debug("Response OK, the file successfully returned by the cluster peer. "); if (entity != null) { entityContent = entity.getContent(); ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = entityContent.read(buffer)) > -1) { arrayOutputStream.write(buffer, 0, len); } arrayOutputStream.flush(); inputStream = new ByteArrayInputStream(arrayOutputStream.toByteArray()); } } else if (statusCode == HttpStatus.SC_NO_CONTENT) { if (HttpDelete.METHOD_NAME.equals(operation)) { LOGGER.info("Deletion of the file {} was successful.", fileName); } } else if (statusCode == HttpStatus.SC_FORBIDDEN) { LOGGER.error("The access to the report with the name {} is forbidden.", fileName); String error = "The access to the report " + fileName + " is forbidden."; throw new SecurityViolationException(error); } else if (statusCode == HttpStatus.SC_NOT_FOUND) { String error = "The report file " + fileName + " was not found on the originating nodes filesystem."; throw new ObjectNotFoundException(error); } } catch (ClientProtocolException e) { String error = "An exception with the communication protocol has occurred during a query to the cluster peer. " + e.getLocalizedMessage(); throw new CommunicationException(error); } } else { LOGGER.error( "Cluster pattern parameters is empty, please refer to the documentation and set up the parameter value accordingly"); throw new ConfigurationException( "Cluster pattern parameters is empty, please refer to the documentation and set up the parameter value accordingly"); } } catch (URISyntaxException e1) { throw new CommunicationException("Invalid uri syntax: " + e1.getLocalizedMessage()); } catch (UnsupportedEncodingException e) { LOGGER.error("Unhandled exception when listing nodes"); LoggingUtils.logUnexpectedException(LOGGER, "Unhandled exception when listing nodes", e); } finally { IOUtils.closeQuietly(entityContent); } return inputStream; }
From source file:ca.psiphon.tunneledwebview.MainActivity.java
private static byte[] readInputStreamToBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int readCount; byte[] buffer = new byte[16384]; while ((readCount = inputStream.read(buffer, 0, buffer.length)) != -1) { outputStream.write(buffer, 0, readCount); }/*from ww w.j av a2s . c o m*/ outputStream.flush(); inputStream.close(); return outputStream.toByteArray(); }
From source file:Main.java
/** * Utility method that creates a <code>UIDefaults.LazyValue</code> that * creates an <code>ImageIcon</code> <code>UIResource</code> for the * specified image file name. The image is loaded using * <code>getResourceAsStream</code>, starting with a call to that method * on the base class parameter. If it cannot be found, searching will * continue through the base class' inheritance hierarchy, up to and * including <code>rootClass</code>. * * @param baseClass the first class to use in searching for the resource * @param rootClass an ancestor of <code>baseClass</code> to finish the * search at//from w ww .j av a2 s . c o m * @param imageFile the name of the file to be found * @return a lazy value that creates the <code>ImageIcon</code> * <code>UIResource</code> for the image, * or null if it cannot be found */ public static Object makeIcon(final Class<?> baseClass, final Class<?> rootClass, final String imageFile) { return new UIDefaults.LazyValue() { public Object createValue(UIDefaults table) { /* Copy resource into a byte array. This is * necessary because several browsers consider * Class.getResource a security risk because it * can be used to load additional classes. * Class.getResourceAsStream just returns raw * bytes, which we can convert to an image. */ byte[] buffer = java.security.AccessController .doPrivileged(new java.security.PrivilegedAction<byte[]>() { public byte[] run() { try { InputStream resource = null; Class<?> srchClass = baseClass; while (srchClass != null) { resource = srchClass.getResourceAsStream(imageFile); if (resource != null || srchClass == rootClass) { break; } srchClass = srchClass.getSuperclass(); } if (resource == null) { return null; } BufferedInputStream in = new BufferedInputStream(resource); ByteArrayOutputStream out = new ByteArrayOutputStream(1024); byte[] buffer = new byte[1024]; int n; while ((n = in.read(buffer)) > 0) { out.write(buffer, 0, n); } in.close(); out.flush(); return out.toByteArray(); } catch (IOException ioe) { System.err.println(ioe.toString()); } return null; } }); if (buffer == null) { return null; } if (buffer.length == 0) { System.err.println("warning: " + imageFile + " is zero-length"); return null; } return new ImageIconUIResource(buffer); } }; }