Example usage for java.io ByteArrayOutputStream toString

List of usage examples for java.io ByteArrayOutputStream toString

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream toString.

Prototype

public synchronized String toString() 

Source Link

Document

Converts the buffer's contents into a string decoding bytes using the platform's default character set.

Usage

From source file:com.thelastcheck.commons.buffer.ByteArrayDumpFormatter.java

/**
 * Will print a hexdump output of a byte array to defined output stream. If
 * the stream parameter is null, then the output will be to the log.
 * /*from   www .  j av a 2s. co  m*/
 * @param title
 * @param byteArray
 * @param out
 */
private static void dumpByteArray(String title, byte[] byteArray, OutputStream out) {
    int estimatedSizeOfHexdump = byteArray.length * 75;
    ByteArrayOutputStream dumpOut = new ByteArrayOutputStream(estimatedSizeOfHexdump);
    try {
        HexDump.dump(byteArray, 0, dumpOut, 0);
        if (out == null) {
            logDump.debug(title + NEWLINE + dumpOut.toString());
        } else {
            out.write(new Date().toString().getBytes());
            out.write((byte) NEWLINE);
            out.write(title.getBytes());
            out.write((byte) NEWLINE);
            out.write(dumpOut.toByteArray());
            out.write((byte) NEWLINE);
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        logDump.error("ArrayIndexOutOfBoundsException", e);
    } catch (IllegalArgumentException e) {
        logDump.error("IllegalArgumentException", e);
    } catch (IOException e) {
        logDump.error("IOException", e);
    }
}

From source file:Main.java

public static String readTextFile(InputStream inputStream) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    byte buf[] = new byte[1024];
    int len;/* w w w .j  a  va  2  s  .  c  o m*/
    try {
        while ((len = inputStream.read(buf)) != -1) {
            outputStream.write(buf, 0, len);
        }
        outputStream.close();
        inputStream.close();
    } catch (IOException e) {

    }
    return outputStream.toString();
}

From source file:Main.java

/**
 * returns an XML string.//from   w ww.  j  a  v  a  2s.c o m
 *
 * @param pDocument         Document XML DOM document
 * @return                  String XML string
 */
public static String getXML(Document pDocument) throws Exception {
    String retString = null;
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        serializer.transform(new DOMSource(pDocument), new StreamResult(out));
        retString = out.toString();
        out.close();
    } catch (Exception ex) {
        throw new Exception(ex.getMessage());
    }
    return retString;
}

From source file:Main.java

private static String readInStream(FileInputStream inStream) {
    try {/* w ww. ja  va2  s.com*/
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[512];
        int length = -1;
        while ((length = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, length);
        }

        outStream.close();
        inStream.close();
        return outStream.toString();
    } catch (IOException e) {
        Log.i("FileTest", e.getMessage());
    }
    return null;
}

From source file:Main.java

private static String readInStream(FileInputStream inStream) {
    try {//from w  ww .j  a va 2s  .  c om
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[512];
        int length = -1;
        while ((length = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, length);
        }

        outStream.close();
        inStream.close();
        return outStream.toString();
    } catch (IOException e) {
        // UIHelper.Log("e", "", "FileReadError", true);
    }
    return null;
}

From source file:XMLUtils.java

public static String toString(Node node, int indent) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    writeTo(node, out, indent);/*  w w w .j ava  2  s .  c o  m*/
    return out.toString();
}

From source file:com.googlecode.jmxtrans.model.output.GraphiteWriterTests.java

private static String getOutput(Server server, Query query, Result result) throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GraphiteWriter writer = getGraphiteWriter(out);
    writer.doWrite(server, query, of(result));
    return out.toString();
}

From source file:Main.java

public static String readRawTextFile(Context ctx, int resId) {
    InputStream inputStream = ctx.getResources().openRawResource(resId);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    int i;//from   w  ww.  ja va2 s. c o m
    try {
        i = inputStream.read();
        while (i != -1) {
            byteArrayOutputStream.write(i);
            i = inputStream.read();
        }
        inputStream.close();
    } catch (IOException e) {
        return null;
    }
    return byteArrayOutputStream.toString();
}

From source file:edu.dfci.cccb.mev.analysis.Limma.java

public static void execute(Heatmap heatmap, String selection1, String selection2, final File output,
        final File significant, final File rnk, String dimension)
        throws IOException, ScriptException, AnnotationNotFoundException {
    try (final Provisional input = file();
            final Provisional configuration = file();
            final Provisional script = file();
            final OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(script))) {
        if ("row".equals(dimension))
            configureRows(new FileOutputStream(configuration), heatmap, selection1, selection2);
        else/*from  www.ja  v a 2s  .  c om*/
            configureColumns(new FileOutputStream(configuration), heatmap, selection1, selection2);
        heatmap.toStream(new FileOutputStream(input));
        if (log.isDebugEnabled())
            try (BufferedReader readBack = new BufferedReader(new FileReader(input))) {
                log.debug("Dump line 1: \"" + readBack.readLine() + "\"");
                log.debug("Dump line 2: \"" + readBack.readLine() + "\"");
            }
        velocity.getTemplate(Limma.script).merge(new VelocityContext(new HashMap<String, String>() {
            private static final long serialVersionUID = 1L;

            {
                if (log.isDebugEnabled())
                    log.debug("Running LIMMA with input " + input.getAbsolutePath() + " configuration "
                            + configuration.getAbsolutePath() + " output " + output.getAbsolutePath()
                            + " significant " + significant);
                put("input", input.getAbsolutePath());
                put("configuration", configuration.getAbsolutePath());
                put("output", output.getAbsolutePath());
                put("significant", significant.getAbsolutePath());
                put("rnk", rnk.getAbsolutePath());
            }
        }), writer);
        writer.flush();
        Process r = Runtime.getRuntime().exec(Limma.r + " " + script.getAbsolutePath());
        try {
            r.waitFor();
        } catch (InterruptedException e) {
            log.error("Interrupted while waiting for R", e);
        }
        if (log.isDebugEnabled()) {
            ByteArrayOutputStream listing = new ByteArrayOutputStream();
            IOUtils.copy(r.getErrorStream(), listing);
            log.debug("Return value " + r.exitValue() + " error output:\n" + listing.toString());
        }
        if (r.exitValue() != 0)
            throw new RuntimeException("Non zero return value from R process " + r.exitValue());
        // r.eval (new InputStreamReader (new ByteArrayInputStream
        // (script.toByteArray ())));
    }
}

From source file:com.jkoolcloud.tnt4j.streams.inputs.WsStream.java

/**
 * Performs JAX-WS service call using SOAP API.
 *
 * @param url/*w  w w .ja va  2s  .  c  o m*/
 *            JAX-WS service URL
 * @param soapRequestData
 *            JAX-WS service request data: headers and body XML string
 * @return service response string
 * @throws Exception
 *             if exception occurs while performing JAX-WS service call
 */
protected static String callWebService(String url, String soapRequestData) throws Exception {
    if (StringUtils.isEmpty(url)) {
        LOGGER.log(OpLevel.DEBUG, StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME,
                "WsStream.cant.execute.request"), url);
        return null;
    }

    LOGGER.log(OpLevel.DEBUG,
            StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME, "WsStream.invoking.request"),
            url, soapRequestData);

    Map<String, String> headers = new HashMap<>();
    // separate SOAP message header values from request body XML
    BufferedReader br = new BufferedReader(new StringReader(soapRequestData));
    StringBuilder sb = new StringBuilder();
    try {
        String line;
        while ((line = br.readLine()) != null) {
            if (line.trim().startsWith("<")) { // NON-NLS
                sb.append(line).append(Utils.NEW_LINE);
            } else {
                int bi = line.indexOf(':'); // NON-NLS
                if (bi >= 0) {
                    String hKey = line.substring(0, bi).trim();
                    String hValue = line.substring(bi + 1).trim();
                    headers.put(hKey, hValue);
                } else {
                    sb.append(line).append(Utils.NEW_LINE);
                }
            }
        }
    } finally {
        Utils.close(br);
    }

    soapRequestData = sb.toString();

    LOGGER.log(OpLevel.DEBUG,
            StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME, "WsStream.invoking.request"),
            url, soapRequestData);

    // Create Request body XML document
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(soapRequestData)));

    // Create SOAP Connection
    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection soapConnection = soapConnectionFactory.createConnection();

    // Create SOAP message and set request XML as body
    SOAPMessage soapRequest = MessageFactory.newInstance().createMessage();

    // SOAPPart part = soapRequest.getSOAPPart();
    // SOAPEnvelope envelope = part.getEnvelope();
    // envelope.addNamespaceDeclaration();

    if (!headers.isEmpty()) {
        MimeHeaders mimeHeaders = soapRequest.getMimeHeaders();

        for (Map.Entry<String, String> e : headers.entrySet()) {
            mimeHeaders.addHeader(e.getKey(), e.getValue());
        }
    }

    SOAPBody body = soapRequest.getSOAPBody();
    body.addDocument(doc);
    soapRequest.saveChanges();

    // Send SOAP Message to SOAP Server
    SOAPMessage soapResponse = soapConnection.call(soapRequest, url);

    ByteArrayOutputStream soapResponseBaos = new ByteArrayOutputStream();
    soapResponse.writeTo(soapResponseBaos);
    String soapResponseXml = soapResponseBaos.toString();

    return soapResponseXml;
}