List of usage examples for java.io ByteArrayOutputStream toString
public synchronized String toString()
From source file:com.vmware.identity.rest.core.server.util.VerificationUtil.java
private static String getMD5(ContainerRequestContext context) { if (!context.hasEntity()) { return ""; }//from w w w. jav a 2 s .co m InputStream in = context.getEntityStream(); try { ByteArrayOutputStream out = new ByteArrayOutputStream(in.available()); final byte[] data = new byte[ReaderWriter.BUFFER_SIZE]; int len = 0; while ((len = in.read(data)) > 0) { out.write(data, 0, len); } // Reset our entity stream since we consumed it and it may need to be read for object marshalling context.setEntityStream(new ByteArrayInputStream(out.toByteArray())); return RequestSigner.computeMD5(out.toString()); } catch (IOException e) { throw new IllegalArgumentException(e); } }
From source file:com.recomdata.datasetexplorer.proxy.XmlHttpProxy.java
public static JSONObject loadJSONObject(InputStream in) { ByteArrayOutputStream out = null; try {// w w w . ja v a 2 s . co m byte[] buffer = new byte[1024]; int read = 0; out = new ByteArrayOutputStream(); while (true) { read = in.read(buffer); if (read <= 0) break; out.write(buffer, 0, read); } return new JSONObject(out.toString()); } catch (Exception e) { getLogger().severe("XmlHttpProxy error reading in json " + e); } finally { try { if (in != null) { in.close(); } if (out != null) { out.flush(); out.close(); } } catch (Exception e) { } } return null; }
From source file:com.boundlessgeo.wps.grass.GrassProcesses.java
@DescribeProcess(title = "GRASS Version", description = "Retreive the version of GRASS used for computation") @DescribeResult(description = "Version") public static String version() { if (EXEC == null) { return "unavailable"; }//from w ww .j a va 2 s . c o m CommandLine cmd = new CommandLine(EXEC); cmd.addArgument("-v"); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); executor.setWatchdog(watchdog); try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(outputStream)); LOGGER.info("exec: " + cmd.toString()); int exitValue = executor.execute(cmd); return outputStream.toString(); } catch (ExecuteException huh) { return "exit code: " + huh.getExitValue() + " (" + huh.getMessage() + ")"; } catch (IOException e) { return "unavailable: " + e.getClass().getSimpleName() + ":" + e.getMessage(); } }
From source file:org.LinuxdistroCommunity.android.client.NetworkUtilities.java
static String readStreamToString(InputStream stream, int block_size) throws IOException, UnsupportedEncodingException { InputStream in = stream;// w w w. j ava 2s.co m ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] pBuffer = new byte[block_size]; try { for (;;) { int res = in.read(pBuffer); if (res == -1) { break; } if (res > 0) { if (out != null) { out.write(pBuffer, 0, res); } } } out.close(); in.close(); in = null; return out.toString(); } finally { if (in != null) { try { in.close(); } catch (Throwable t) { /* Ignore me */ } } if (out != null) { try { out.close(); } catch (Throwable t) { /* Ignore me */ } } } }
From source file:com.streamsets.pipeline.kafka.common.KafkaTestUtil.java
public static List<KeyedMessage<String, String>> produceJsonMessages(String topic, String partition) throws IOException { ContextExtensions ctx = (ContextExtensions) ContextInfoCreator.createTargetContext("", false, OnRecordError.TO_ERROR);// w w w.java2s .c om List<KeyedMessage<String, String>> messages = new ArrayList<>(); for (Record record : produce20Records()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); RecordWriter rw = ctx.createRecordWriter(baos); rw.write(record); rw.close(); messages.add(new KeyedMessage<>(topic, partition, baos.toString())); } return messages; }
From source file:Main.java
/** * Apply some indentiation to some XML. This method is not very sophisticated and will * not cope well with anything but the simplest XML (no CDATA etc). The algorithm used does * not look at element names and does not actually parse the XML. It also assumes that the * forward slash and greater-than at the end of a self-terminating tag and not seperated by * ant whitespace.//from www .j a v a2 s .c o m * * @param xmlString input XML fragment * @return indented XML fragment */ public static String indentXmlSimple(String xmlString) { ByteArrayOutputStream os = new ByteArrayOutputStream(); int indent = 0; byte[] bytes = xmlString.getBytes(); int i = 0; while (i < bytes.length) { if (bytes[i] == '<' && bytes[i + 1] == '/') { os.write('\n'); writeIndentation(os, --indent); } else if (bytes[i] == '<') { if (i > 0) { os.write('\n'); } writeIndentation(os, indent++); } else if (bytes[i] == '/' && bytes[i + 1] == '>') { indent--; } else if (bytes[i] == '>') { } os.write(bytes[i++]); } return os.toString(); }
From source file:XmlUtil.java
/** * Apply some indentiation to some XML. This method is not very * sophisticated and will not cope well with anything but the simplest XML * (no CDATA etc). The algorithm used does not look at element names and * does not actually parse the XML. It also assumes that the forward slash * and greater-than at the end of a self-terminating tag and not seperated * by ant whitespace./* w w w . j av a 2 s . co m*/ * * @param xmlString * input XML fragment * @return indented XML fragment */ public static String indentXmlSimple(String xmlString) { ByteArrayOutputStream os = new ByteArrayOutputStream(); int indent = 0; char bytes[] = xmlString.toCharArray(); int i = 0; while (i < bytes.length) { if (bytes[i] == '<' && bytes[i + 1] == '/') { os.write('\n'); writeIndentation(os, --indent); } else if (bytes[i] == '<') { if (i > 0) { os.write('\n'); } writeIndentation(os, indent++); } else if (bytes[i] == '/' && bytes[i + 1] == '>') { indent--; } else if (bytes[i] == '>') { } os.write(bytes[i++]); } return os.toString(); }
From source file:com.android.repository.util.InstallerUtil.java
/** * Unzips the given zipped input stream into the given directory. * * @param in The (zipped) input stream. * @param out The directory into which to expand the files. Must exist. * @param fop The {@link FileOp} to use for file operations. * @param expectedSize Compressed size of the stream. * @param progress Currently only used for logging. * @throws IOException If we're unable to read or write. *//*from w w w .j a v a 2 s . com*/ public static void unzip(@NonNull File in, @NonNull File out, @NonNull FileOp fop, long expectedSize, @NonNull ProgressIndicator progress) throws IOException { if (!fop.exists(out) || !fop.isDirectory(out)) { throw new IllegalArgumentException("out must exist and be a directory."); } // ZipFile requires an actual (not mock) file, so make sure we have a real one. in = fop.ensureRealFile(in); progress.setText("Unzipping..."); ZipFile zipFile = new ZipFile(in); try { Enumeration entries = zipFile.getEntries(); progress.setFraction(0); while (entries.hasMoreElements()) { ZipArchiveEntry entry = (ZipArchiveEntry) entries.nextElement(); String name = entry.getName(); File entryFile = new File(out, name); progress.setSecondaryText(name); if (entry.isUnixSymlink()) { ByteArrayOutputStream targetByteStream = new ByteArrayOutputStream(); readZipEntry(zipFile, entry, targetByteStream, expectedSize, progress); Path linkPath = fop.toPath(entryFile); Path linkTarget = fop.toPath(new File(targetByteStream.toString())); Files.createSymbolicLink(linkPath, linkTarget); } else if (entry.isDirectory()) { if (!fop.exists(entryFile)) { if (!fop.mkdirs(entryFile)) { progress.logWarning("failed to mkdirs " + entryFile); } } } else { if (!fop.exists(entryFile)) { File parent = entryFile.getParentFile(); if (parent != null && !fop.exists(parent)) { fop.mkdirs(parent); } if (!fop.createNewFile(entryFile)) { throw new IOException("Failed to create file " + entryFile); } } OutputStream unzippedOutput = fop.newFileOutputStream(entryFile); if (readZipEntry(zipFile, entry, unzippedOutput, expectedSize, progress)) { return; } if (!fop.isWindows()) { // get the mode and test if it contains the executable bit int mode = entry.getUnixMode(); //noinspection OctalInteger if ((mode & 0111) != 0) { try { fop.setExecutablePermission(entryFile); } catch (IOException ignore) { } } } } } } finally { ZipFile.closeQuietly(zipFile); } }
From source file:org.fuin.owndeb.commons.DebUtils.java
private static void execute(final CommandLine cmdLine, final File workingDir, final String errorMsg) { LOG.debug("Execute: " + cmdLine.toString()); final Executor executor = new DefaultExecutor(); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final PumpStreamHandler psh = new PumpStreamHandler(bos); executor.setStreamHandler(psh);/*from w ww. jav a2s .co m*/ executor.setWorkingDirectory(workingDir); try { final int result = executor.execute(cmdLine); if (result != 0) { logError(asList(bos.toString())); throw new RuntimeException("Error # " + result + " / " + errorMsg); } } catch (final IOException ex) { logError(asList(bos.toString())); throw new RuntimeException(errorMsg, ex); } }
From source file:eu.planets_project.tb.gui.backing.admin.wsclient.util.WSClient.java
/** * Invokes an operation using SAAJ/* ww w . j a v a2s. c om*/ * * @param operation The operation to invoke */ public static String invokeOperation(OperationInfo operation) throws Exception { try { // Determine if the operation style is RPC boolean isRPC = false; if (operation.getStyle() != null) isRPC = operation.getStyle().equalsIgnoreCase("rpc"); else ; // All connections are created by using a connection factory SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance(); // Now we can create a SOAPConnection object using the connection factory SOAPConnection connection = conFactory.createConnection(); // All SOAP messages are created by using a message factory MessageFactory msgFactory = MessageFactory.newInstance(); // Now we can create the SOAP message object SOAPMessage msg = msgFactory.createMessage(); // Get the SOAP part from the SOAP message object SOAPPart soapPart = msg.getSOAPPart(); // The SOAP part object will automatically contain the SOAP envelope SOAPEnvelope envelope = soapPart.getEnvelope(); //my extension - START //envelope.addNamespaceDeclaration("_ns1", operation.getNamespaceURI()); //my extension - END if (isRPC) { // Add namespace declarations to the envelope, usually only required for RPC/encoded envelope.addNamespaceDeclaration(XSI_NAMESPACE_PREFIX, XSI_NAMESPACE_URI); envelope.addNamespaceDeclaration(XSD_NAMESPACE_PREFIX, XSD_NAMESPACE_URI); } // Get the SOAP header from the envelope SOAPHeader header = envelope.getHeader(); // The client does not yet support SOAP headers header.detachNode(); // Get the SOAP body from the envelope and populate it SOAPBody body = envelope.getBody(); // Create the default namespace for the SOAP body //body.addNamespaceDeclaration("", operation.getNamespaceURI()); // Add the service information String targetObjectURI = operation.getTargetObjectURI(); if (targetObjectURI == null) { // The target object URI should not be null targetObjectURI = ""; } // Add the service information //Name svcInfo = envelope.createName(operation.getTargetMethodName(), "", targetObjectURI); Name svcInfo = envelope.createName(operation.getTargetMethodName(), "ns1", operation.getNamespaceURI()); SOAPElement svcElem = body.addChildElement(svcInfo); if (isRPC) { // Set the encoding style of the service element svcElem.setEncodingStyle(operation.getEncodingStyle()); } // Add the message contents to the SOAP body Document doc = XMLSupport.readXML(operation.getInputMessageText()); if (doc.hasRootElement()) { // Begin building content buildSoapElement(envelope, svcElem, doc.getRootElement(), isRPC); } //svcElem.addTextNode(operation.getInputMessageText()); //svcElem. // Check for a SOAPAction String soapActionURI = operation.getSoapActionURI(); if (soapActionURI != null && soapActionURI.length() > 0) { // Add the SOAPAction value as a MIME header MimeHeaders mimeHeaders = msg.getMimeHeaders(); mimeHeaders.setHeader("SOAPAction", "\"" + operation.getSoapActionURI() + "\""); } // Save changes to the message we just populated msg.saveChanges(); // Get ready for the invocation URLEndpoint endpoint = new URLEndpoint(operation.getTargetURL()); // Show the URL endpoint message in the log ByteArrayOutputStream msgStream = new ByteArrayOutputStream(); msg.writeTo(msgStream); log.debug("SOAP Message MeasurementTarget URL: " + endpoint.getURL()); log.debug("SOAP Request: " + msgStream.toString()); // Make the call SOAPMessage response = connection.call(msg, endpoint); // Close the connection, we are done with it connection.close(); // Get the content of the SOAP response Source responseContent = response.getSOAPPart().getContent(); // Convert the SOAP response into a JDOM TransformerFactory tFact = TransformerFactory.newInstance(); Transformer transformer = tFact.newTransformer(); JDOMResult jdomResult = new JDOMResult(); transformer.transform(responseContent, jdomResult); // Get the document created by the transform operation Document responseDoc = jdomResult.getDocument(); // Send the response to the Log String strResponse = XMLSupport.outputString(responseDoc); log.debug("SOAP Response from: " + operation.getTargetMethodName() + ": " + strResponse); // Set the response as the output message operation.setOutputMessageText(strResponse); // Return the response generated return strResponse; } catch (Throwable ex) { throw new Exception("Error invoking operation", ex); } }