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.pieframework.model.repository.ModelStore.java

protected static String componentToString(Object component) throws SimpleSerializerException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DefaultSerializer.write(component, out);
    return out.toString();
}

From source file:jatoo.image.metadata.exiftool.ExifToolImageMetadataHandler.java

private static String exec(String... arguments) {

    try {//ww w .  ja va  2s  .  co  m
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        int code = COMMAND.exec(buffer, arguments);

        if (code == 0) {

            String exec = buffer.toString().trim();

            if (exec.length() == 0) {
                return null;
            }

            else {
                return exec;
            }
        }

        else {
            throw new IOException("anormal exec termination (code = " + code + "): " + buffer.toString());
        }
    }

    catch (IOException | InterruptedException e) {
        logger.error("error executing command (" + Arrays.toString(arguments) + ")", e);
        return null;
    }
}

From source file:net.ripe.rpki.commons.crypto.x509cert.X509CertificateUtil.java

/**
 * Get a base 64-encoded, DER-encoded X.509 subjectPublicKeyInfo as used for the Trust Anchor Locator (TAL)
 *
 * @throws X509CertificateOperationException
 *
 * @throws IOException/*  ww w.  j a  va  2  s . c om*/
 */
public static String getEncodedSubjectPublicKeyInfo(X509Certificate certificate) {

    byte[] tbsCertificate;
    try {
        tbsCertificate = certificate.getTBSCertificate();
    } catch (CertificateEncodingException e) {
        throw new X509CertificateOperationException("Can't extract TBSCertificate from certificate", e);
    }
    ASN1Sequence tbsCertificateSequence = (ASN1Sequence) Asn1Util.decode(tbsCertificate);
    TBSCertificateStructure tbsCertificateStructure = new TBSCertificateStructure(tbsCertificateSequence);
    SubjectPublicKeyInfo subjectPublicKeyInfo = tbsCertificateStructure.getSubjectPublicKeyInfo();

    try {
        byte[] data = subjectPublicKeyInfo.getEncoded();
        Base64Encoder encoder = new Base64Encoder();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        encoder.encode(data, 0, data.length, out);
        out.flush();
        return out.toString();
    } catch (IOException e) {
        throw new X509CertificateOperationException("Can't encode SubjectPublicKeyInfo for certificate", e);
    }
}

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

public static String doPost(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);

    HttpPost request = new HttpPost(page);
    HttpResponse response = null;//from ww  w  . j  a  va 2  s.co 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));
    }

    UrlEncodedFormEntity uf = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
    request.setEntity(uf);
    request.setHeader("Content-Type", POST_MIME_TYPE);

    // 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, null);
        Log.e(TAG, 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

        return sbResponse.toString();
    }
}

From source file:com.antsdb.saltedfish.util.UberUtil.java

public static String hexDump(byte[] bytes) {
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    try {/*from   w  w w  . j  a v  a  2s  .co m*/
        HexDump.dump(bytes, 0, buf, 0);
        return buf.toString();
    } catch (Exception x) {
    }
    return "";
}

From source file:com.samsung.sjs.ExplanationsTest.java

private static String explainErrors(JSEnvironment env, String sourceCode) {
    AstRoot root = new Parser().parse(sourceCode, "", 1);
    SatSolver sat = new Sat4J();
    SJSTypeTheory theory = new SJSTypeTheory(env, null, root);
    List<Integer> hard = new ArrayList<>();
    List<Integer> soft = new ArrayList<>();
    List<ITypeConstraint> constraints = theory.getConstraints();
    for (int i = 0; i < constraints.size(); ++i) {
        (theory.hackyGenerator().hasExplanation(constraints.get(i)) ? soft : hard).add(i);
    }//from  w  ww  .  j  a  v  a 2s  .co m
    Pair<TypeAssignment, Collection<Integer>> result = TheorySolver.solve(theory, new SatFixingSetFinder<>(sat),
            hard, soft);
    ConstraintGenerator g = theory.hackyGenerator();
    StringBuilder buf = new StringBuilder();
    for (int broken : result.getRight()) {
        ITypeConstraint c = theory.hackyConstraintAccess().get(broken);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        g.explainFailure(c, result.getLeft()).prettyprint(new PrintStream(stream));
        buf.append(stream.toString());
    }
    return buf.toString();
}

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

public static String doPost(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);

    HttpPost request = new HttpPost(page);
    HttpResponse response = null;//w  w w . jav  a  2  s .  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));
    }

    UrlEncodedFormEntity uf = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
    request.setEntity(uf);
    request.setHeader("Content-Type", POST_MIME_TYPE);

    // 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);

        RWHtmlLog.e(TAG, "Error status code = " + status, null);
        RWHtmlLog.e(TAG, ostream.toString(), null);

        throw new Exception(HTTP_POST_FAILED + status);
    } 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

/**
 * Read a text file into a String, optionally limiting the length.
 * // ww  w  .ja  va 2s. c om
 * @param file
 *            to read (will not seek, so things like /proc files are OK)
 * @param max
 *            length (positive for head, negative of tail, 0 for no limit)
 * @param ellipsis
 *            to add of the file was truncated (can be null)
 * @return the contents of the file, possibly truncated
 * @throws IOException
 *             if something goes wrong reading the file
 */
public static String readTextFile(File file, int max, String ellipsis) throws IOException {
    InputStream input = new FileInputStream(file);
    try {
        long size = file.length();
        if (max > 0 || (size > 0 && max == 0)) { // "head" mode: read the
                                                 // first N bytes
            if (size > 0 && (max == 0 || size < max))
                max = (int) size;
            byte[] data = new byte[max + 1];
            int length = input.read(data);
            if (length <= 0)
                return "";
            if (length <= max)
                return new String(data, 0, length);
            if (ellipsis == null)
                return new String(data, 0, max);
            return new String(data, 0, max) + ellipsis;
        } else if (max < 0) { // "tail" mode: keep the last N
            int len;
            boolean rolled = false;
            byte[] last = null, data = null;
            do {
                if (last != null)
                    rolled = true;
                byte[] tmp = last;
                last = data;
                data = tmp;
                if (data == null)
                    data = new byte[-max];
                len = input.read(data);
            } while (len == data.length);

            if (last == null && len <= 0)
                return "";
            if (last == null)
                return new String(data, 0, len);
            if (len > 0) {
                rolled = true;
                System.arraycopy(last, len, last, 0, last.length - len);
                System.arraycopy(data, 0, last, last.length - len, len);
            }
            if (ellipsis == null || !rolled)
                return new String(last);
            return ellipsis + new String(last);
        } else { // "cat" mode: size unknown, read it all in streaming
                 // fashion
            ByteArrayOutputStream contents = new ByteArrayOutputStream();
            int len;
            byte[] data = new byte[1024];
            do {
                len = input.read(data);
                if (len > 0)
                    contents.write(data, 0, len);
            } while (len == data.length);
            return contents.toString();
        }
    } finally {
        input.close();
    }
}

From source file:eml.studio.server.util.HDFSIO.java

/**
 * The same method as hdfs dfs -cat//from  w ww.j  a  v a  2s. com
 * @param uri target file uri
 * @return  content string in file
 * @throws IOException
 */
public static String cat(String uri) throws IOException {
    InputStream in = getInputStream(uri);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    IOUtils.copyBytes(in, out, 4096, true);
    return out.toString();
}

From source file:Main.java

public static byte[] encodeObject(Object object, final boolean noisy) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    XMLEncoder encoder = new XMLEncoder(outputStream);
    encoder.setExceptionListener(new ExceptionListener() {
        public void exceptionThrown(Exception ex) {
            if (noisy)
                ex.printStackTrace();//from  w  w  w  . jav  a  2s  .co  m
        }
    });

    encoder.writeObject(object);
    encoder.close();

    if (noisy)
        System.out.println(outputStream.toString());

    return outputStream.toByteArray();
}