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:Main.java

public static String getExceptionCauseString(final Throwable ex) {
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final PrintStream ps = new PrintStream(bos);

    try {//  w w w  .ja  v  a  2  s .c o  m
        // print directly
        Throwable t = ex;
        while (t.getCause() != null) {
            t = t.getCause();
        }
        t.printStackTrace(ps);
        return toVisualString(bos.toString());
    } finally {
        try {
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:fr.cls.atoll.motu.library.misc.utils.PropertiesUtilities.java

/**
 * Replace from an input stream the names of system variables that follows the scheme ${var}
 * <tt> by their corresponding values.
 * //from w w w . j a  v a2  s .c o  m
 * @param in the input stream for which the variables has to be replaced.
 * @return a brand new imput stream with system variables replaced with values.
 * @throws IOException
 */
static public InputStream replaceSystemVariable(InputStream in) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {
        IOUtils.copy(in, out);
    } finally {
        IOUtils.closeQuietly(out);
    }

    String inStr = out.toString();
    String outStr = replaceSystemVariable(inStr);

    return new ByteArrayInputStream(outStr.getBytes());
}

From source file:Main.java

public static String readFile(Activity activity, String fileName) {
    AssetManager assets = activity.getAssets();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    byte buf[] = new byte[1024];
    int len;/*from ww w . ja va  2s .  c  o m*/
    try {
        InputStream inputStream = assets.open(fileName);
        while ((len = inputStream.read(buf)) != -1) {
            outputStream.write(buf, 0, len);
        }
        outputStream.close();
        inputStream.close();
        return outputStream.toString();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:info.guardianproject.net.http.HttpManager.java

public static String doPost(String serviceEndpoint, Properties props) throws Exception {

    DefaultHttpClient httpClient = new SocksHttpClient();

    HttpPost request = new HttpPost(serviceEndpoint);
    HttpResponse response = null;//  w ww . j  a v a  2  s .c  o  m
    HttpEntity entity = null;

    StringBuffer sbResponse = new StringBuffer();

    Enumeration<Object> enumProps = props.keys();
    String key, value = null;

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();

    while (enumProps.hasMoreElements()) {
        key = (String) enumProps.nextElement();
        value = (String) props.get(key);
        nvps.add(new BasicNameValuePair(key, value));

        Log.i(TAG, "adding nvp:" + key + "=" + value);
    }

    UrlEncodedFormEntity uf = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);

    Log.i(TAG, uf.toString());

    request.setEntity(uf);

    request.setHeader("Content-Type", POST_MIME_TYPE);

    Log.i(TAG, "http post request: " + request.toString());

    // Post, check and show the result (not really spectacular, but works):
    response = httpClient.execute(request);
    entity = response.getEntity();

    int status = response.getStatusLine().getStatusCode();

    // we assume that the response body contains the error message
    if (status != HttpStatus.SC_OK) {
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        entity.writeTo(ostream);

        Log.e(TAG, " error status code=" + status);
        Log.e(TAG, ostream.toString());

        return null;
    } else {
        InputStream content = response.getEntity().getContent();
        // <consume response>

        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;

        while ((line = reader.readLine()) != null)
            sbResponse.append(line);

        content.close(); // this will also close the connection

        return sbResponse.toString();
    }

}

From source file:com.openideals.android.net.HttpManager.java

public static String doPost(String serviceEndpoint, Properties props) throws Exception {

    HttpClient httpClient = new DefaultHttpClient();

    HttpPost request = new HttpPost(serviceEndpoint);
    HttpResponse response = null;/*ww  w. j a v a  2s.c  om*/
    HttpEntity entity = null;

    StringBuffer sbResponse = new StringBuffer();

    Enumeration<Object> enumProps = props.keys();
    String key, value = null;

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();

    while (enumProps.hasMoreElements()) {
        key = (String) enumProps.nextElement();
        value = (String) props.get(key);
        nvps.add(new BasicNameValuePair(key, value));

        Log.i(TAG, "adding nvp:" + key + "=" + value);
    }

    UrlEncodedFormEntity uf = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);

    Log.i(TAG, uf.toString());

    request.setEntity(uf);

    request.setHeader("Content-Type", POST_MIME_TYPE);

    Log.i(TAG, "http post request: " + request.toString());

    // Post, check and show the result (not really spectacular, but works):
    response = httpClient.execute(request);
    entity = response.getEntity();

    int status = response.getStatusLine().getStatusCode();

    // we assume that the response body contains the error message
    if (status != HttpStatus.SC_OK) {
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        entity.writeTo(ostream);

        Log.e(TAG, " error status code=" + status);
        Log.e(TAG, ostream.toString());

        return null;
    } else {
        InputStream content = response.getEntity().getContent();
        // <consume response>

        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;

        while ((line = reader.readLine()) != null)
            sbResponse.append(line);

        content.close(); // this will also close the connection

        return sbResponse.toString();
    }

}

From source file:Main.java

public final static String getStringFormRaw(Context context, int rawId) {
    ByteArrayOutputStream baos = null;
    InputStream in = context.getResources().openRawResource(rawId);
    try {//from   ww w . ja v a 2 s  . c  o m
        baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = in.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        baos.close();
        return baos.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return "";
    } finally {
        if (baos != null) {
            try {
                baos.close();
                baos = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:co.cask.cdap.logging.appender.file.TestFileLogging.java

@BeforeClass
public static void setUpContext() throws Exception {
    dsFramework = new InMemoryDatasetFramework(new InMemoryDefinitionRegistryFactory());
    dsFramework.addModule("table", new InMemoryOrderedTableModule());

    LoggingContextAccessor//from w w  w  .  j ava  2 s .  c o m
            .setLoggingContext(new FlowletLoggingContext("TFL_ACCT_1", "APP_1", "FLOW_1", "FLOWLET_1"));
    logBaseDir = "/tmp/log_files_" + new Random(System.currentTimeMillis()).nextLong();

    CConfiguration cConf = CConfiguration.create();
    cConf.set(LoggingConfiguration.LOG_BASE_DIR, logBaseDir);
    cConf.setInt(LoggingConfiguration.LOG_MAX_FILE_SIZE_BYTES, 20 * 1024);

    Configuration conf = HBaseConfiguration.create();
    cConf.copyTxProperties(conf);
    TransactionManager txManager = new TransactionManager(conf);
    txManager.startAndWait();
    txClient = new InMemoryTxSystemClient(txManager);

    LogAppender appender = new AsyncLogAppender(
            new FileLogAppender(cConf, dsFramework, txClient, new LocalLocationFactory()));
    new LogAppenderInitializer(appender).initialize("TestFileLogging");

    Logger logger = LoggerFactory.getLogger("TestFileLogging");
    for (int i = 0; i < 60; ++i) {
        Exception e1 = new Exception("Test Exception1");
        Exception e2 = new Exception("Test Exception2", e1);
        logger.warn("Test log message " + i + " {} {}", "arg1", "arg2", e2);
    }

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    StatusPrinter.setPrintStream(new PrintStream(bos));
    StatusPrinter.print((LoggerContext) LoggerFactory.getILoggerFactory());
    System.out.println(bos.toString());

    appender.stop();
}

From source file:com.halseyburgund.rwframework.core.RWHttpManager.java

public static String doGet(String page, Properties props, int timeOutSec) throws Exception {
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, timeOutSec * 1000);
    HttpConnectionParams.setSoTimeout(httpParams, timeOutSec * 1000);

    HttpClient httpClient = new DefaultHttpClient(httpParams);

    StringBuilder uriBuilder = new StringBuilder(page);

    StringBuffer sbResponse = new StringBuffer();

    Enumeration<Object> enumProps = props.keys();
    String key, value = null;//from www .j  a v a2  s  .  co m

    uriBuilder.append('?');

    while (enumProps.hasMoreElements()) {
        key = enumProps.nextElement().toString();
        value = props.get(key).toString();
        uriBuilder.append(key);
        uriBuilder.append('=');
        uriBuilder.append(java.net.URLEncoder.encode(value));
        if (enumProps.hasMoreElements()) {
            uriBuilder.append('&');
        }
    }

    if (D) {
        Log.d(TAG, "GET request: " + uriBuilder.toString(), null);
    }

    HttpGet request = new HttpGet(uriBuilder.toString());
    HttpResponse response = httpClient.execute(request);

    int status = response.getStatusLine().getStatusCode();

    // we assume that the response body contains the error message
    if (status != HttpStatus.SC_OK) {
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        response.getEntity().writeTo(ostream);
        Log.e(TAG, "GET ERROR: " + ostream.toString(), null);
        throw new HttpException(String.valueOf(status));
    } else {
        InputStream content = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = reader.readLine()) != null) {
            sbResponse.append(line);
        }
        content.close(); // this will also close the connection
    }

    if (D) {
        Log.d(TAG, "GET response: " + sbResponse.toString(), null);
    }

    return sbResponse.toString();
}

From source file:com.newrelic.agent.Deployments.java

private static String getDeploymentPayload(String appName, CommandLine cmd)
        /* 103:    */ throws IOException
/* 104:    */ {//from w  w w.  j  a  va  2  s  .c  o m
    /* 105: 98 */ StringBuilder builder = new StringBuilder();
    /* 106: 99 */ builder.append("deployment[timestamp]=").append(System.currentTimeMillis());
    /* 107:    */
    /* 108:101 */ builder.append("&deployment[appname]=").append(URLEncoder.encode(appName, "UTF-8"));
    /* 109:102 */ if (cmd.getArgs().length > 1) {
        /* 110:103 */ builder.append("&deployment[description]=")
                .append(URLEncoder.encode(cmd.getArgs()[1], "UTF-8"));
        /* 111:    */ }
    /* 112:105 */ if (cmd.hasOption("user")) {
        /* 113:106 */ builder.append("&deployment[user]=")
                .append(URLEncoder.encode(cmd.getOptionValue("user"), "UTF-8"));
        /* 114:    */ }
    /* 115:108 */ if (cmd.hasOption("revision")) {
        /* 116:109 */ builder.append("&deployment[revision]=")
                .append(URLEncoder.encode(cmd.getOptionValue("revision"), "UTF-8"));
        /* 117:    */ }
    /* 118:112 */ if (cmd.hasOption("changes"))
    /* 119:    */ {
        /* 120:113 */ System.out.println("Reading the change log from standard input...");
        /* 121:    */ try
        /* 122:    */ {
            /* 123:115 */ ByteArrayOutputStream output = new ByteArrayOutputStream();
            /* 124:116 */ Streams.copy(System.in, output);
            /* 125:    */
            /* 126:118 */ builder.append("&deployment[changelog]=")
                    .append(URLEncoder.encode(output.toString(), "UTF-8"));
            /* 127:    */ }
        /* 128:    */ catch (IOException ex)
        /* 129:    */ {
            /* 130:120 */ throw new IOException("An error occurred reading the change log from standard input",
                    ex);
            /* 131:    */ }
        /* 132:    */ }
    /* 133:124 */ return builder.toString();
    /* 134:    */ }

From source file:com.halseyburgund.roundware.server.RWHttpManager.java

public static String doGet(String page, Properties props) throws Exception {
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT_MSEC);
    HttpConnectionParams.setSoTimeout(httpParams, CONNECTION_TIMEOUT_MSEC);

    HttpClient httpClient = new DefaultHttpClient(httpParams);

    StringBuilder uriBuilder = new StringBuilder(page);

    StringBuffer sbResponse = new StringBuffer();

    Enumeration<Object> enumProps = props.keys();
    String key, value = null;/*from  w w  w.  j av  a 2 s . c om*/

    uriBuilder.append('?');

    while (enumProps.hasMoreElements()) {
        key = enumProps.nextElement().toString();
        value = props.get(key).toString();
        uriBuilder.append(key);
        uriBuilder.append('=');
        uriBuilder.append(java.net.URLEncoder.encode(value));
        if (enumProps.hasMoreElements()) {
            uriBuilder.append('&');
        }
    }

    if (D) {
        RWHtmlLog.i(TAG, "GET request: " + uriBuilder.toString(), null);
    }

    HttpGet request = new HttpGet(uriBuilder.toString());
    HttpResponse response = httpClient.execute(request);

    int status = response.getStatusLine().getStatusCode();

    // we assume that the response body contains the error message
    if (status != HttpStatus.SC_OK) {
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        response.getEntity().writeTo(ostream);
        RWHtmlLog.e(TAG, "GET ERROR: " + ostream.toString(), null);

        throw new Exception(HTTP_POST_FAILED + status);

    } else {
        InputStream content = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = reader.readLine()) != null) {
            sbResponse.append(line);
        }
        content.close(); // this will also close the connection
    }

    if (D) {
        RWHtmlLog.i(TAG, "GET response: " + sbResponse.toString(), null);
    }

    return sbResponse.toString();
}