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:br.com.dgimenes.jsonlibscomparison.JSONLibsTest.java

private static String encodeWithJACKSONJAXB(SalesJAXB salesAnnotatedWithJAXB)
        throws JsonGenerationException, JsonMappingException, IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ObjectMapper mapper = new ObjectMapper();
    @SuppressWarnings("deprecation")
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
    // enables "JAXB annotations only" mode
    mapper.setAnnotationIntrospector(introspector);
    mapper.writeValue(outputStream, salesAnnotatedWithJAXB);
    return outputStream.toString();
}

From source file:org.devtcg.five.util.streaming.FailfastHttpClient.java

/**
 * Generates a cURL command equivalent to the given request.
 *//*from  www  .  ja  v a 2 s .com*/
private static String toCurl(HttpUriRequest request) throws IOException {
    StringBuilder builder = new StringBuilder();

    builder.append("curl ");

    for (Header header : request.getAllHeaders()) {
        builder.append("--header \"");
        builder.append(header.toString().trim());
        builder.append("\" ");
    }

    URI uri = request.getURI();

    // If this is a wrapped request, use the URI from the original
    // request instead. getURI() on the wrapper seems to return a
    // relative URI. We want an absolute URI.
    if (request instanceof RequestWrapper) {
        HttpRequest original = ((RequestWrapper) request).getOriginal();
        if (original instanceof HttpUriRequest) {
            uri = ((HttpUriRequest) original).getURI();
        }
    }

    builder.append("\"");
    builder.append(uri);
    builder.append("\"");

    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
        HttpEntity entity = entityRequest.getEntity();
        if (entity != null && entity.isRepeatable()) {
            if (entity.getContentLength() < 1024) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                entity.writeTo(stream);
                String entityString = stream.toString();

                // TODO: Check the content type, too.
                builder.append(" --data-ascii \"").append(entityString).append("\"");
            } else {
                builder.append(" [TOO MUCH DATA TO INCLUDE]");
            }
        }
    }

    return builder.toString();
}

From source file:net.solarnetwork.node.util.ClassUtils.java

/**
 * Load a classpath SQL resource into a String.
 * //w  w  w  .  j  a  va2  s.  c om
 * @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

private static String getAaptResult(String sdkPath, String apkPath, final Pattern pattern) {
    try {//from w  ww . j a va2  s .co  m
        final File apkFile = new File(apkPath);
        final ByteArrayOutputStream aaptOutput = new ByteArrayOutputStream();
        final String command = getAaptDumpBadgingCommand(sdkPath, apkFile.getName());

        Process process = Runtime.getRuntime().exec(command, null, apkFile.getParentFile());

        InputStream inputStream = process.getInputStream();
        for (int last = inputStream.read(); last != -1; last = inputStream.read()) {
            aaptOutput.write(last);
        }

        String packageId = "";
        final String aaptResult = aaptOutput.toString();
        if (aaptResult.length() > 0) {
            final Matcher matcher = pattern.matcher(aaptResult);
            if (matcher.find()) {
                packageId = matcher.group(1);
            }
        }
        return packageId;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:net.solarnetwork.util.ClassUtils.java

/**
 * Load a classpath SQL resource into a String.
 * /* w  w  w . ja  v a2s. co 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.runwaysdk.controller.ErrorUtility.java

private static String decompress(String message) {
    try {/*from  w w w .j  av  a  2 s  . com*/
        byte[] bytes = Base64.decode(message);

        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        BufferedInputStream bufis = new BufferedInputStream(new GZIPInputStream(bis));
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len;
        while ((len = bufis.read(buf)) > 0) {
            bos.write(buf, 0, len);
        }
        String retval = bos.toString();
        bis.close();
        bufis.close();
        bos.close();
        return retval;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.jrummyapps.busybox.signing.ZipSigner.java

/**
 * Write a .SF file with a digest the specified manifest.
 *///from  www. j  a va 2  s  . c  o m
private static byte[] writeSignatureFile(Manifest manifest, OutputStream out)
        throws IOException, GeneralSecurityException {
    final Manifest sf = new Manifest();
    final Attributes main = sf.getMainAttributes();
    main.putValue("Manifest-Version", MANIFEST_VERSION);
    main.putValue("Created-By", CREATED_BY);

    final MessageDigest md = MessageDigest.getInstance("SHA1");
    final PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true,
            "UTF-8");

    // Digest of the entire manifest
    manifest.write(print);
    print.flush();
    main.putValue("SHA1-Digest-Manifest", base64encode(md.digest()));

    final Map<String, Attributes> entries = manifest.getEntries();
    for (final Map.Entry<String, Attributes> entry : entries.entrySet()) {
        // Digest of the manifest stanza for this entry.
        print.print("Name: " + entry.getKey() + "\r\n");
        for (final Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
            print.print(att.getKey() + ": " + att.getValue() + "\r\n");
        }
        print.print("\r\n");
        print.flush();

        final Attributes sfAttr = new Attributes();
        sfAttr.putValue("SHA1-Digest", base64encode(md.digest()));
        sf.getEntries().put(entry.getKey(), sfAttr);
    }

    final ByteArrayOutputStream sos = new ByteArrayOutputStream();
    sf.write(sos);

    String value = sos.toString();
    String done = value.replace("Manifest-Version", "Signature-Version");

    out.write(done.getBytes());

    print.close();
    sos.close();

    return done.getBytes();
}

From source file:Main.java

public static String getResourceText(Context context, int resId) {
    InputStream is = null;/*from   ww w  .j av a2 s .  co  m*/
    BufferedInputStream bis;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        is = context.getResources().openRawResource(resId);
        bis = new BufferedInputStream(is);
        int result = bis.read();
        while (result != -1) {
            byte b = (byte) result;
            baos.write(b);
            result = bis.read();
        }
    } catch (IOException e) {
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
        }
    }
    return baos.toString();
}

From source file:com.novoda.commons.net.httpclient.NovodaHttpClient.java

/**
 * Generates a cURL command equivalent to the given request.
 *//* w  w  w  .  j  a  va  2s .  c om*/
private static String toCurl(HttpUriRequest request, boolean logAuthToken) throws IOException {
    StringBuilder builder = new StringBuilder();

    builder.append("curl ");

    for (Header header : request.getAllHeaders()) {
        if (!logAuthToken && (header.getName().equals("Authorization") || header.getName().equals("Cookie"))) {
            continue;
        }
        builder.append("--header \"");
        builder.append(header.toString().trim());
        builder.append("\" ");
    }

    URI uri = request.getURI();

    // If this is a wrapped request, use the URI from the original
    // request instead. getURI() on the wrapper seems to return a
    // relative URI. We want an absolute URI.
    if (request instanceof RequestWrapper) {
        HttpRequest original = ((RequestWrapper) request).getOriginal();
        if (original instanceof HttpUriRequest) {
            uri = ((HttpUriRequest) original).getURI();
        }
    }

    builder.append("\"");
    builder.append(uri);
    builder.append("\"");

    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
        HttpEntity entity = entityRequest.getEntity();
        if (entity != null && entity.isRepeatable()) {
            if (entity.getContentLength() < 1024) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                entity.writeTo(stream);
                String entityString = stream.toString();

                builder.append(" --data-ascii \"").append(entityString).append("\"");
            } else {
                builder.append(" [TOO MUCH DATA TO INCLUDE]");
            }
        }
    }

    return builder.toString();
}

From source file:com.ginstr.android.service.opencellid.library.data.ApiKeyHandler.java

/**
 * Query server to generate a new random API key.
 * Use this if you don't want to register at opencellid.org to
 * get a random key to upload/download data.
 * This function will store the retrieved key to a file.
 * // w w w  . j  a va  2s  . com
 * @return valid API key or null if call failed
 */
private static String requestNewKey(boolean testMode) {
    // get a key from server and store it on the SD card
    String responseFromServer = null;

    try {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(OpenCellIdLibContext.getServerURL(testMode) + KEY_GENERATOR_URL_DEFAULT);

        Log.d(ApiKeyHandler.class.getSimpleName(),
                "Connecting to " + KEY_GENERATOR_URL_DEFAULT + " for a new API key...");

        HttpResponse result = httpclient.execute(httpGet);

        StatusLine status = result.getStatusLine();
        if (status.getStatusCode() == 200) {

            if (result.getEntity() != null) {
                InputStream is = result.getEntity().getContent();

                ByteArrayOutputStream content = new ByteArrayOutputStream();

                // Read response into a buffered stream
                int readBytes = 0;
                byte[] sBuffer = new byte[4096];

                while ((readBytes = is.read(sBuffer)) != -1) {
                    content.write(sBuffer, 0, readBytes);
                }

                responseFromServer = content.toString();

                result.getEntity().consumeContent();
            }
            Log.d(ApiKeyHandler.class.getSimpleName(), "New API key set => " + responseFromServer);

            //store new key into defined file
            writeApiKeyToFile(responseFromServer, testMode);
            return responseFromServer;
        } else {
            Log.d(ApiKeyHandler.class.getSimpleName(),
                    "Returned " + status.getStatusCode() + " " + status.getReasonPhrase());
        }

        httpclient = null;
        httpGet = null;
        result = null;

    } catch (Exception e) {
        Log.e(ApiKeyHandler.class.getSimpleName(), "", e);
    }

    return null;
}