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

@Deprecated
public synchronized String toString(int hibyte) 

Source Link

Document

Creates a newly allocated string.

Usage

From source file:org.paxml.util.PaxmlUtils.java

public static String readStreamToString(InputStream in, String encoding) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {/*  w ww . j  a  v  a2  s. co  m*/
        IOUtils.copy(in, out);
        return out.toString(encoding == null ? "UTF-8" : encoding);
    } catch (IOException e) {
        throw new PaxmlRuntimeException(e);
    }
}

From source file:io.lavagna.web.support.ResourceController.java

private static List<String> prepareTemplates(ServletContext context, String initialPath) throws IOException {
    List<String> r = new ArrayList<>();
    BeforeAfter ba = new AngularTemplate();
    for (String file : allFilesWithExtension(context, initialPath, ".html")) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        output(file, context, os, ba);//w w  w.ja v a 2s . c o  m
        r.add(os.toString(StandardCharsets.UTF_8.displayName()));
    }
    return r;
}

From source file:com.glaf.core.security.DigestUtil.java

public static String digestString(String password, String algorithm) {
    if (password == null || password.trim().length() == 0) {
        return password;
    }//w w  w. ja va  2 s.  co  m
    if (conf.getBoolean("password.enc", true)) {
        MessageDigest md = null;
        ByteArrayOutputStream bos = null;
        OutputStream encodedStream = null;
        try {
            md = MessageDigest.getInstance(algorithm);
            byte[] digest = md.digest(password.getBytes("UTF-8"));
            bos = new ByteArrayOutputStream();
            encodedStream = MimeUtility.encode(bos, "base64");
            encodedStream.write(digest);
            return bos.toString("UTF-8");
        } catch (IOException ioe) {
            throw new RuntimeException("Fatal error: " + ioe);
        } catch (NoSuchAlgorithmException ae) {
            throw new RuntimeException("Fatal error: " + ae);
        } catch (MessagingException me) {
            throw new RuntimeException("Fatal error: " + me);
        } finally {
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(encodedStream);
        }
    }
    return password;
}

From source file:org.alfresco.bm.tools.BMTestRunner.java

/**
 * Helper method to extract the csv results to a string that can be output in the logs
 *//*w w  w .  j  a  v  a  2 s  .c om*/
public static String getResultsCSV(ResultsRestAPI resultsAPI) {
    // Get the summary CSV results for the time period and check some of the values
    StreamingOutput out = resultsAPI.getReportCSV();
    ByteArrayOutputStream bos = new ByteArrayOutputStream(2048);
    String summary = "";
    try {
        out.write(bos);
        summary = bos.toString("UTF-8");
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            bos.close();
        } catch (Exception e) {
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("BM000X summary report: \n" + summary);
    }
    return summary;
}

From source file:net.roboconf.agent.internal.misc.UserDataUtils.java

/**
 * Configures the agent from VMWare.//w  ww  . j a  v a  2  s  .c  o  m
 * @param logger a logger
 * @return the agent's data, or null if they could not be parsed
 */
public static AgentProperties findParametersForVmware(Logger logger) {

    File propertiesFile = new File("/tmp/roboconf.properties");
    try {
        int retries = 30;
        while ((!propertiesFile.exists() || !propertiesFile.canRead()) && retries-- > 0) {
            logger.fine("Agent tries to read properties file " + propertiesFile + ": trial #" + (30 - retries));
            try {
                Thread.sleep(2000);

            } catch (InterruptedException e) {
                throw new IOException("Can't read properties file: " + e);
            }
        }

        AgentProperties result = AgentProperties.readIaasProperties(Utils.readPropertiesFile(propertiesFile));

        /*
         * HACK for specific IaaS configurations (using properties file in a VMWare-like manner)
         * Try to pick IP address... in the case we are on OpenStack or any IaaS with amazon-compatible API
         * Some configurations (with floating IPs) do not provide network interfaces exposing public IPs !
         */
        InputStream in = null;
        try {
            URL userDataUrl = new URL("http://169.254.169.254/latest/meta-data/public-ipv4");
            in = userDataUrl.openStream();
            ByteArrayOutputStream os = new ByteArrayOutputStream();

            Utils.copyStreamSafely(in, os);
            String ip = os.toString("UTF-8");
            if (!AgentUtils.isValidIP(ip)) {
                // Failed retrieving public IP: try private one instead
                Utils.closeQuietly(in);
                userDataUrl = new URL("http://169.254.169.254/latest/meta-data/local-ipv4");
                in = userDataUrl.openStream();
                os = new ByteArrayOutputStream();

                Utils.copyStreamSafely(in, os);
                ip = os.toString("UTF-8");
            }

            if (AgentUtils.isValidIP(ip))
                result.setIpAddress(os.toString("UTF-8"));

        } catch (IOException e) {
            Utils.logException(logger, e);
        } finally {
            Utils.closeQuietly(in);
        }
        /* HACK ends here (see comment above). Removing it is harmless on classical VMWare configurations. */

        return result;

    } catch (IOException e) {
        logger.fine("Agent failed to read properties file " + propertiesFile);
        return null;
    }
}

From source file:com.pannous.es.reindex.MySearchResponseJson.java

public static String readString(InputStream inputStream, String encoding) throws IOException {
    InputStream in = new BufferedInputStream(inputStream);
    try {/*w  w  w  .j  a v  a2s  . c o m*/
        byte[] buffer = new byte[4096];
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        int numRead;
        while ((numRead = in.read(buffer)) != -1) {
            output.write(buffer, 0, numRead);
        }
        return output.toString(encoding);
    } finally {
        in.close();
    }
}

From source file:com.buaa.cfs.utils.ReflectionUtils.java

/**
 * Log the current thread stacks at INFO level.
 *
 * @param log         the logger that logs the stack trace
 * @param title       a descriptive title for the call stacks
 * @param minInterval the minimum time from the last
 *///from  w w  w . j  a  v a2 s .  c o m
public static void logThreadInfo(Log log, String title, long minInterval) {
    boolean dumpStack = false;
    if (log.isInfoEnabled()) {
        synchronized (ReflectionUtils.class) {
            long now = Time.now();
            if (now - previousLogTime >= minInterval * 1000) {
                previousLogTime = now;
                dumpStack = true;
            }
        }
        if (dumpStack) {
            try {
                ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                printThreadInfo(new PrintStream(buffer, false, "UTF-8"), title);
                log.info(buffer.toString(Charset.defaultCharset().name()));
            } catch (UnsupportedEncodingException ignored) {
            }
        }
    }
}

From source file:de.nrw.hbz.deepzoomer.fileUtil.FileUtil.java

public static String loadFileIntoString(File file) {
    String fString = null;// www.j  a va2 s.  c om
    FileInputStream fis = null;

    try {
        fis = new FileInputStream(file);
        int i = (int) file.length();
        byte[] b = new byte[i];
        fis.read(b);

        ByteArrayOutputStream bfos = new ByteArrayOutputStream();
        bfos.write(b);

        fString = bfos.toString("UTF-8");

    } catch (Exception e) {
        // TODO Auto-generated catch block
        log.error(e);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }

    }

    return fString;
}

From source file:com.smartsheet.utils.HttpUtils.java

/**
 * Gets the JSON payload (as a String) returned by invoking HTTP GET on the
 * specified URL, with the optional accessToken and userToAssume arguments.
 *///from ww w  .j av a 2 s .c o m
public static String getJsonPayload(String url, String accessToken, String userToAssume) throws IOException {

    HttpGet httpGet = newGetRequest(url, accessToken, ACCEPT_JSON_HEADER, userToAssume);
    HttpResponse response = getResponse(httpGet);
    try {
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == ServiceUnavailableException.SERVICE_UNAVAILABLE_CODE)
            throw new ServiceUnavailableException(url);

        InputStream content = getContentOnSuccess(response, url, status);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        InputStream inStream = new BufferedInputStream(content);
        OutputStream outStream = new BufferedOutputStream(byteArrayOutputStream);
        copyAndClose(inStream, outStream);

        return byteArrayOutputStream.toString(CHARSET);

    } finally {
        httpGet.releaseConnection();
    }
}

From source file:com.net2plan.utils.HTMLUtils.java

/**
 * Converts an XML file to a formatted HTML output via an XSLT definition.
 * //from  w w w  .  j av  a2s .c  o m
 * @param xml String containing an XML file
 * @param xsl URL containing an XSLT definition
 * @return Formatted HTML output
 */
public static String getHTMLFromXML(String xml, URL xsl) {
    try {
        Source xmlDoc = new StreamSource(new StringReader(xml));
        Source xslDoc = new StreamSource(xsl.openStream());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer(xslDoc);
        transformer.transform(xmlDoc, new StreamResult(baos));
        String html = baos.toString(StandardCharsets.UTF_8.name());
        html = prepareImagePath(html, xsl);
        return html;
    } catch (IOException | TransformerFactoryConfigurationError | TransformerException e) {
        throw new RuntimeException(e);
    }
}