List of usage examples for java.io ByteArrayOutputStream flush
public void flush() throws IOException
From source file:de.mpg.escidoc.services.aa.crypto.RSAEncoder.java
public static String rsaDecrypt(String[] string) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrivateKey privateKey = (PrivateKey) readKeyFromFile(Config.getProperty("escidoc.aa.private.key.file"), false);/*from www . j a v a2 s. com*/ Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); for (String part : string) { byte[] inArr = Base64.decodeBase64(part.getBytes("UTF-8")); baos.write(cipher.doFinal(inArr)); baos.flush(); } return new String(baos.toByteArray(), "UTF-8"); }
From source file:com.mirth.connect.connectors.jms.JmsMessageUtils.java
public static Object getObjectForMessage(Message source) throws JMSException { Object result = null;/*w ww.ja v a 2s. co m*/ try { if (source instanceof ObjectMessage) { result = ((ObjectMessage) source).getObject(); } else if (source instanceof MapMessage) { Hashtable map = new Hashtable(); MapMessage m = (MapMessage) source; for (Enumeration e = m.getMapNames(); e.hasMoreElements();) { String name = (String) e.nextElement(); Object obj = m.getObject(name); map.put(name, obj); } result = map; } else if (source instanceof javax.jms.BytesMessage) { javax.jms.BytesMessage bm = (javax.jms.BytesMessage) source; java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 4]; int len = 0; bm.reset(); while ((len = bm.readBytes(buffer)) != -1) { baos.write(buffer, 0, len); } baos.flush(); result = baos.toByteArray(); baos.close(); if (result != null) { if (logger.isDebugEnabled()) logger.debug("JMSToObject: extracted " + ((byte[]) result).length + " bytes from JMS BytesMessage"); } } else if (source instanceof TextMessage) { result = ((TextMessage) source).getText(); } else if (source instanceof BytesMessage) { byte[] bytes = getBytesFromMessage(source); return CompressionHelper.uncompressByteArray(bytes); } else if (source instanceof StreamMessage) { StreamMessage sm = (javax.jms.StreamMessage) source; result = new java.util.Vector(); try { Object obj = null; while ((obj = sm.readObject()) != null) { ((java.util.Vector) result).addElement(obj); } } catch (MessageEOFException eof) { } catch (Exception e) { throw new JMSException("Failed to extract information from JMS Stream Message: " + e); } } else { result = source; } } catch (Exception e) { throw new JMSException("Failed to transform message: " + e.getMessage()); } return result; }
From source file:Main.java
public static File saveBitmapToExternal(Bitmap bitmap, String targetFileDirPath) { if (bitmap == null || bitmap.isRecycled()) { return null; }//from w w w . ja v a 2s. co m File targetFileDir = new File(targetFileDirPath); if (!targetFileDir.exists() && !targetFileDir.mkdirs()) { return null; } File targetFile = new File(targetFileDir, UUID.randomUUID().toString()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); FileOutputStream fos = null; try { fos = new FileOutputStream(targetFile); baos.writeTo(fos); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } finally { try { baos.flush(); baos.close(); } catch (IOException e) { e.printStackTrace(); } try { if (fos != null) { fos.flush(); fos.close(); } } catch (IOException e) { e.printStackTrace(); } } return targetFile; }
From source file:net.wastl.webmail.xml.XMLCommon.java
/** * Logs a XML dump to the specified Log instanance. * * <P>For brevity and simplicity, callers may want to import level * constants like this so they can juse use like "LOG_LEVEL_DEBUG": import static org.apache.commons.logging.impl.SimpleLog.*; * </P>/*from w w w.j a v a 2 s . c om*/ * N.b. the calling method and location can't be identified by this * method. If you need that kind of detail, make a direct log call * before calling this method. * * @param log Target Log instance * @param label Leading log message * @param level A org.apache.commons.logging.impl.SimpleLog constant. * I don't know why Commons doesn't have a simple log() * method and Log.X constants like Log4j does. :( * @param doc The XML document to dump */ public static synchronized void dumpXML(Log log, int level, String label, Document doc) { String methodName = null; switch (level) { case LOG_LEVEL_DEBUG: methodName = "debug"; break; case LOG_LEVEL_ERROR: methodName = "error"; break; case LOG_LEVEL_FATAL: methodName = "fatal"; break; case LOG_LEVEL_INFO: methodName = "info"; break; case LOG_LEVEL_TRACE: methodName = "trace"; break; case LOG_LEVEL_WARN: methodName = "warn"; break; } if (methodName == null) throw new IllegalArgumentException("Unexpected level specification " + level + "\nSee API spec document for " + SimpleLog.class.getName()); try { java.lang.reflect.Method logMethod = Log.class.getMethod(methodName, Object.class); ByteArrayOutputStream baos = new ByteArrayOutputStream(); writeXML(doc, baos, "test"); baos.flush(); logMethod.invoke(log, label + "\n" + baos); } catch (Exception ex) { log.fatal("Failed to log XML document details", ex); return; } }
From source file:de.qaware.chronix.converter.common.Compression.java
/*** * Compressed the given stream using gzip. * * @param stream the input stream/*from w w w . ja va 2 s . c om*/ * @return an byte[] with the compressed data from the stream */ public static byte[] compressFromStream(InputStream stream) { if (stream == null) { LOGGER.debug("Stream is null. Returning null."); return null; } ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); OutputStream zippedStream = null; try { zippedStream = new GZIPOutputStream(byteArrayOutputStream); int nRead; byte[] data = new byte[16384]; while ((nRead = stream.read(data, 0, data.length)) != -1) { zippedStream.write(data, 0, nRead); } zippedStream.flush(); byteArrayOutputStream.flush(); } catch (IOException e) { LOGGER.error("Exception occurred while compressing gzip stream.", e); return null; } finally { IOUtils.closeQuietly(zippedStream); IOUtils.closeQuietly(byteArrayOutputStream); } return byteArrayOutputStream.toByteArray(); }
From source file:com.datatorrent.stram.StramLocalCluster.java
public static LogicalPlan cloneLogicalPlan(LogicalPlan lp) throws IOException, ClassNotFoundException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); LogicalPlan.write(lp, bos);// ww w . j a v a 2s . c om LOG.debug("serialized size: {}", bos.toByteArray().length); bos.flush(); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); return LogicalPlan.read(bis); }
From source file:org.apache.geode.internal.util.IOUtils.java
/** * Reads the contents of the specified InputStream into a byte array. * <p/>/* w w w . j a v a2 s . co m*/ * * @param in the InputStream to read content from. * @return a byte array containing the content of the specified InputStream. * @throws IOException if an I/O error occurs while reading the InputStream. * @see java.io.ByteArrayOutputStream * @see java.io.InputStream */ public static byte[] toByteArray(final InputStream in) throws IOException { assert in != null : "The input stream to read bytes from cannot be null!"; final ByteArrayOutputStream out = new ByteArrayOutputStream(); final byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; try { while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); out.flush(); } } finally { IOUtils.close(in); IOUtils.close(out); } return out.toByteArray(); }
From source file:org.apache.torque.util.VillageUtils.java
/** * Converts a hashtable to a byte array for storage/serialization. * * @param hash The Hashtable to convert. * * @return A byte[] with the converted Hashtable. * * @throws Exception If an error occurs. *//* w w w . j av a 2 s .c o m*/ public static byte[] hashtableToByteArray(final Hashtable hash) throws Exception { Hashtable saveData = new Hashtable(hash.size()); byte[] byteArray = null; Iterator keys = hash.entrySet().iterator(); while (keys.hasNext()) { Map.Entry entry = (Map.Entry) keys.next(); if (entry.getValue() instanceof Serializable) { saveData.put(entry.getKey(), entry.getValue()); } } ByteArrayOutputStream baos = null; BufferedOutputStream bos = null; ObjectOutputStream out = null; try { // These objects are closed in the finally. baos = new ByteArrayOutputStream(); bos = new BufferedOutputStream(baos); out = new ObjectOutputStream(bos); out.writeObject(saveData); out.flush(); bos.flush(); baos.flush(); byteArray = baos.toByteArray(); } finally { close(out); close(bos); close(baos); } return byteArray; }
From source file:net.pterodactylus.sone.web.ajax.JsonPage.java
/** * Returns a byte array containing the stack trace of the given throwable. * * @param t/*from w w w . j av a 2 s . co m*/ * The throwable whose stack trace to dump into an array * @return The array with the stack trace, or an empty array if the stack * trace could not be dumped */ private static byte[] dumpStackTrace(Throwable t) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); OutputStreamWriter writer = null; PrintWriter printWriter = null; try { writer = new OutputStreamWriter(byteArrayOutputStream, "uTF-8"); printWriter = new PrintWriter(writer); t.printStackTrace(printWriter); byteArrayOutputStream.flush(); return byteArrayOutputStream.toByteArray(); } catch (IOException ioe1) { /* quite not possible. */ return new byte[0]; } finally { Closer.close(printWriter); Closer.close(writer); Closer.close(byteArrayOutputStream); } }
From source file:org.wso2.carbon.core.transports.util.XsdUtil.java
public static void printXsd(CarbonHttpRequest request, CarbonHttpResponse response, ConfigurationContext configCtx, String serviceName, AxisService axisService) throws IOException { if (GhostDeployerUtils.isGhostService(axisService)) { // if the existing service is a ghost service, deploy the actual one axisService = GhostDeployerUtils.deployActualService(configCtx.getAxisConfiguration(), axisService); }//from w w w . ja v a 2s .c o m if (!RequestProcessorUtil.canExposeServiceMetadata(axisService)) { response.setError(HttpStatus.SC_FORBIDDEN, "Access to service metadata for service: " + serviceName + " has been forbidden"); return; } OutputStream outputStream = response.getOutputStream(); String contextRoot = request.getContextPath(); if (axisService == null) { response.addHeader(HTTP.CONTENT_TYPE, "text/html"); response.setError(HttpStatus.SC_NOT_FOUND); outputStream.write( ("<h4>Service " + serviceName + " is not found. Cannot display Schema.</h4>").getBytes()); outputStream.flush(); return; } if (!axisService.isActive()) { response.addHeader(HTTP.CONTENT_TYPE, "text/html"); outputStream .write(("<h4>Service " + serviceName + " is inactive. Cannot display Schema.</h4>").getBytes()); outputStream.flush(); return; } //cater for named xsds - check for the xsd name String uri = request.getQueryString(); if (request.getQueryString().endsWith(".xsd")) { String schemaName = uri.substring(uri.lastIndexOf('=') + 1); Map services = configCtx.getAxisConfiguration().getServices(); AxisService service = (AxisService) services.get(serviceName); if (service != null) { //run the population logic just to be sure service.populateSchemaMappings(); //write out the correct schema Map schemaTable = service.getSchemaMappingTable(); XmlSchema schema = (XmlSchema) schemaTable.get(schemaName); if (schema == null) { int slashIndex = schemaName.lastIndexOf('/'); int dotIndex = schemaName.lastIndexOf('.'); if (slashIndex > 0) { String schemaKey = schemaName.substring(slashIndex + 1, dotIndex); schema = (XmlSchema) schemaTable.get(schemaKey); } } if (schema == null) { int dotIndex = schemaName.indexOf('.'); if (dotIndex > 0) { String schemaKey = schemaName.substring(0, dotIndex); schema = (XmlSchema) schemaTable.get(schemaKey); } } //schema found - write it to the stream if (schema != null) { response.setStatus(HttpStatus.SC_OK); response.addHeader(HTTP.CONTENT_TYPE, "text/xml"); schema.write(response.getOutputStream()); return; } else { InputStream instream = service.getClassLoader() .getResourceAsStream(DeploymentConstants.META_INF + "/" + schemaName); if (instream != null) { response.setStatus(HttpStatus.SC_OK); response.addHeader(HTTP.CONTENT_TYPE, "text/xml"); OutputStream outstream = response.getOutputStream(); boolean checkLength = true; int length = Integer.MAX_VALUE; int nextValue = instream.read(); if (checkLength) { length--; } while (-1 != nextValue && length >= 0) { outstream.write(nextValue); nextValue = instream.read(); if (checkLength) { length--; } } outstream.flush(); return; } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int ret = service.printXSD(baos, schemaName); if (ret > 0) { baos.flush(); instream = new ByteArrayInputStream(baos.toByteArray()); response.setStatus(HttpStatus.SC_OK); response.addHeader(HTTP.CONTENT_TYPE, "text/xml"); OutputStream outstream = response.getOutputStream(); boolean checkLength = true; int length = Integer.MAX_VALUE; int nextValue = instream.read(); if (checkLength) { length--; } while (-1 != nextValue && length >= 0) { outstream.write(nextValue); nextValue = instream.read(); if (checkLength) { length--; } } outstream.flush(); return; } } } } } axisService.populateSchemaMappings(); Map schemaMappingtable = axisService.getSchemaMappingTable(); String xsds = request.getParameter("xsd"); if (xsds != null && xsds.trim().length() != 0) { response.addHeader(HTTP.CONTENT_TYPE, "text/xml"); XmlSchema schema = (XmlSchema) schemaMappingtable.get(xsds); if (schema == null) { int dotIndex = xsds.indexOf('.'); if (dotIndex > 0) { String schemaKey = xsds.substring(0, dotIndex); schema = (XmlSchema) schemaMappingtable.get(schemaKey); } } if (schema != null) { //schema is there - pump it outs schema.write(new OutputStreamWriter(outputStream, "UTF8")); outputStream.flush(); outputStream.close(); } else if (xsds.endsWith(".xsd") && xsds.indexOf("..") == -1) { InputStream in = axisService.getClassLoader() .getResourceAsStream(DeploymentConstants.META_INF + "/" + xsds); if (in != null) { outputStream.write(IOUtils.getStreamAsByteArray(in)); outputStream.flush(); outputStream.close(); } else { response.setError(HttpServletResponse.SC_NOT_FOUND); } } else { String msg = "Invalid schema " + xsds + " requested"; throw new IOException(msg); } return; } ArrayList schemas = axisService.getSchema(); if (schemas.size() == 1) { response.addHeader(HTTP.CONTENT_TYPE, "text/xml"); // Write to the output stream processSchema((XmlSchema) schemas.get(0), outputStream, contextRoot, request); } else { String idParam = request.getParameter("id"); if (idParam != null) { XmlSchema schema = axisService.getSchema(Integer.parseInt(idParam)); if (schema != null) { response.addHeader(HTTP.CONTENT_TYPE, "text/xml"); processSchema(schema, outputStream, contextRoot, request); } else { response.addHeader(HTTP.CONTENT_TYPE, "text/html"); outputStream.write("<h4>Schema not found!</h4>".getBytes()); } } else { /*String ipAddress = "http://" + NetworkUtils.getLocalHostname() + ":" + ServerManager.getInstance().getHttpPort(); String version = ServerConfiguration.getInstance().getFirstProperty("Version"); outputStream.write(("<html><head>" + "<title>WSO2 Web Services Application Server v" + version + "Management Console" + " - " + axisService.getName() + " Service Schema</title>" + "</head>" + "<body>" + "<b>Schemas for " + axisService.getName() + " service</b><br/><br/>").getBytes()); if (schemas.size() != 0) { for (int i = 0; i < schemas.size(); i++) { String st = "<a href=\"" + ipAddress + RequestProcessorUtil.getServiceContextPath(configCtx) + "/" + axisService.getName() + "?xsd&id=" + i + "&" + ServerConstants.HTTPConstants.ANNOTATION + "=true" + "\">Schema " + i + "</a><br/>"; outputStream.write(st.getBytes()); } } else { outputStream.write("<p>No schemas found</p>".getBytes()); } outputStream.write("</body></html>".getBytes());*/ } } }