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

/**
 * Read all from InputStream/*from  ww  w .  j a  v  a2s . c o m*/
 * @param is Stream to read from
 * @param size Guess the size of InputStream contents, give negative for the automatic
 * @return
 */
public static String readFromInputStream(InputStream is, int size) {
    try {
        ByteArrayOutputStream os;
        if (size <= 0) {
            os = new ByteArrayOutputStream();
        } else {
            os = new ByteArrayOutputStream(size);
        }
        byte buffer[] = new byte[4096];
        int len;
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        return os.toString("UTF-8");
    } catch (IOException e) {
        Log.e("SOAP", "readFromInputStream", e);
        return "";
    }
}

From source file:NettyServerHandler.java

public static String compress(String str) throws IOException {
    if (str == null || str.length() == 0) {
        return str;
    }/* w w w  . j a  v  a2s.c o  m*/
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(out);
    gzip.write(str.getBytes());
    gzip.close();
    String outStr = out.toString("ISO-8859-1");
    return outStr;
}

From source file:com.google.enterprise.adaptor.experimental.Sim.java

public static String percentDecode(String encoded) {
    try {/*from  w  ww .  j a  v a  2  s.  c  om*/
        byte bytes[] = encoded.getBytes("ASCII");
        ByteArrayOutputStream decoded = percentDecode(bytes);
        return decoded.toString("UTF-8");
    } catch (UnsupportedEncodingException uee) {
        throw new RuntimeException(uee);
    }
}

From source file:com.baasbox.service.storage.StatisticsService.java

public static String dbConfiguration() {
    if (BaasBoxLogger.isTraceEnabled())
        BaasBoxLogger.trace("Method Start");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos);
    OGlobalConfiguration.dumpConfiguration(ps);
    String content = "";
    try {//from ww  w  . j a  v a 2  s.c o  m
        content = baos.toString("UTF-8");
    } catch (UnsupportedEncodingException e) {
        content = baos.toString();
    }
    if (BaasBoxLogger.isTraceEnabled())
        BaasBoxLogger.trace("Method End");
    return content;
}

From source file:Main.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private static String decryptStringImpl(Context context, final String encryptedText) {
    String plainText = null;//from   ww w .  jav a2  s  . co  m
    try {
        final KeyStore keyStore = getKeyStore(context);

        PrivateKey privateKey = (PrivateKey) keyStore.getKey(KEY_ALIAS, null);

        String algorithm = ALGORITHM_OLD;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            algorithm = ALGORITHM;
        }
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        CipherInputStream cipherInputStream = new CipherInputStream(
                new ByteArrayInputStream(Base64.decode(encryptedText, Base64.DEFAULT)), cipher);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int b;
        while ((b = cipherInputStream.read()) != -1) {
            outputStream.write(b);
        }
        outputStream.close();
        plainText = outputStream.toString("UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return plainText;
}

From source file:ly.stealth.punxsutawney.Marathon.java

private static JSONObject sendRequest(String uri, String method, JSONObject json) throws IOException {
    URL url = new URL(Marathon.url + uri);
    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    try {//w w w. jav  a 2s.c  o m
        c.setRequestMethod(method);

        if (method.equalsIgnoreCase("POST")) {
            byte[] body = json.toString().getBytes("utf-8");
            c.setDoOutput(true);
            c.setRequestProperty("Content-Type", "application/json");
            c.setRequestProperty("Content-Length", "" + body.length);
            c.getOutputStream().write(body);
        }

        return (JSONObject) JSONValue.parse(new InputStreamReader(c.getInputStream(), "utf-8"));
    } catch (IOException e) {
        if (c.getResponseCode() == 404 && method.equals("GET"))
            return null;

        ByteArrayOutputStream response = new ByteArrayOutputStream();
        InputStream err = c.getErrorStream();
        if (err == null)
            throw e;

        Util.copyAndClose(err, response);
        IOException ne = new IOException(e.getMessage() + ": " + response.toString("utf-8"));
        ne.setStackTrace(e.getStackTrace());
        throw ne;
    } finally {
        c.disconnect();
    }
}

From source file:dk.moerks.ratebeermobile.io.NetBroker.java

private static String responseString(HttpResponse response) {
    try {/* ww w.  ja v  a2 s .  co  m*/
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        response.getEntity().writeTo(ostream);
        //return ostream.toString("ISO8859_1");
        return ostream.toString("windows-1252");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:ch.epfl.leb.sass.commandline.CommandLineInterface.java

/**
 * Reads the welcome_text file and prints it to a PrintStream.
 * @param out stream to print to/* w w w. ja v  a2  s  .co m*/
 */
public static void printWelcomeText(PrintStream out) {
    try {
        InputStream inputStream = urlToWelcomeText;
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        String message = result.toString("UTF-8");
        out.print(message + "\n");
    } catch (IOException ex) {
        Logger.getLogger(CommandLineInterface.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:edu.illinois.ncsa.springdata.SpringData.java

/**
 * Convert the object to JSON.// w  ww .  ja v a  2 s .  c o m
 * 
 * @param object
 *            the object to be converted
 * @return a string with the encoded json.
 * @throws IOException
 *             throws an IOException if the object could not be converted.
 */
public static String objectToJSON(Object object) throws IOException {
    ObjectMapper mapper = new ObjectMapper();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mapper.writeValue(baos, object);
    return new String(baos.toString("UTF-8"));
}

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

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

    // Copy the user data
    String userData = "";
    InputStream in = null;
    try {
        URL userDataUrl = new URL("http://169.254.169.254/latest/user-data");
        in = userDataUrl.openStream();
        ByteArrayOutputStream os = new ByteArrayOutputStream();

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

    } catch (IOException e) {
        logger.severe("The agent properties could not be read. " + e.getMessage());
        Utils.logException(logger, e);
    }

    AgentProperties result = null;
    in = null;
    try {
        // Parse the user data
        result = AgentProperties.readIaasProperties(userData, logger);

        // We need to ask our IP address because we may have several network interfaces.
        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))
            throw new IOException("No IP address could be retrieved (either public-ipv4 or local-ipv4)");

        result.setIpAddress(os.toString("UTF-8"));

    } catch (IOException e) {
        logger.severe("The network properties could not be read. " + e.getMessage());
        Utils.logException(logger, e);

    } finally {
        Utils.closeQuietly(in);
    }

    return result;
}