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.anteros.android.synchronism.communication.AndroidHttpClient.java

/**
 * Generates a cURL command equivalent to the given request.
 *//*from w  w  w  .ja va 2s  .c o  m*/
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();

                // 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:ar.com.iron.android.helpers.UrlHelper.java

/**
 * Realiza un request http y toma de la respuesta el cuerpo principal como si fuera un string.<br>
 * Se asume que el servidor responde un texto pequeo como contenido de la respuesta.<br>
 * Utilizar este mtodo con precaucin ya que dependiendo de la respuesta puede excederse la
 * memoria disponible para la aplicacin//from   ww  w.j ava 2  s  .  c o  m
 * 
 * @param remoteUrl
 *            Direccin donde se har un pedido GET y se obtendr la respuesta
 * @return La cadena que representa el cuerpo de la respuesta HTTP devuelta
 */
public static String getStringFrom(String remoteUrl) throws FailedConnectionException {
    InputStream contentStream = getContentStreamFrom(remoteUrl);
    ByteArrayOutputStream outputStream;
    try {
        outputStream = new ByteArrayOutputStream();
        FileHelper.copyTo(outputStream, contentStream);
    } catch (CantCopyException e) {
        throw new FailedConnectionException(
                "No fue posible construir el String con el contenido bajado del servidor", e);
    } finally {
        FileHelper.cerrarStream(contentStream);
    }
    String responseString = outputStream.toString();
    FileHelper.cerrarStream(outputStream);
    return responseString;
}

From source file:dtw.webmail.model.JwmaMessagePartImpl.java

/**
 * Creates a <tt>JwmaMessagePartImpl</tt> instance from a given
 * <tt>javax.mail.Part</tt> instance.
 *
 * @param part a <tt>javax.mail.Part</tt> instance.
 * @param number the number of the part as <tt>int</tt>.
 *
 * @return the newly created instance./*from   ww w  .j a v a2  s  .  c o m*/
 * @throws JwmaException if it fails to create the new instance.
 */
public static JwmaMessagePartImpl createJwmaMessagePartImpl(Part part, int number) throws JwmaException {
    JwmaMessagePartImpl partinfo = new JwmaMessagePartImpl(part, number);

    //content type
    try {
        partinfo.setContentType(part.getContentType());

        //size
        int size = part.getSize();
        //JwmaKernel.getReference().debugLog().write("Part size="+size);
        String fileName = part.getFileName();
        //correct size of encoded parts
        String[] encoding = part.getHeader("Content-Transfer-Encoding");
        if (fileName != null && encoding != null && encoding.length > 0
                && (encoding[0].equalsIgnoreCase("base64") || encoding[0].equalsIgnoreCase("uuencode"))) {
            if ((fileName.startsWith("=?GB2312?B?") && fileName.endsWith("?="))) {
                byte[] decoded = Base64.decodeBase64(fileName.substring(11, fileName.indexOf("?=")).getBytes());
                fileName = new String(decoded, "GB2312");
                /*fileName = CipherUtils.decrypt(fileName);
                System.out.println("fileName----"+fileName);*/
                //fileName = getFromBASE64(fileName.substring(11,fileName.indexOf("?=")));  
            } else if ((fileName.startsWith("=?UTF-8?") || fileName.startsWith("=?UTF8?"))
                    && fileName.endsWith("?=")) {
                fileName = MimeUtility.decodeText(fileName);
            }
            //an encoded file is about 35% smaller in reality,
            //so correct the size
            size = (int) (size * 0.65);
        }

        partinfo.setSize(size);
        //description
        partinfo.setDescription(part.getDescription());

        //filename
        partinfo.setName(fileName);

        //textcontent
        if (partinfo.isMimeType("text/*")) {
            Object content = part.getContent();
            if (content instanceof String) {
                partinfo.setTextContent((String) content);
            } else if (content instanceof InputStream) {
                InputStream in = (InputStream) content;
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                byte[] buffer = new byte[8192];
                int amount = 0;
                while ((amount = in.read(buffer)) >= 0) {
                    bout.write(buffer, 0, amount);
                }
                partinfo.setTextContent(new String(bout.toString()));
            }
        }
    } catch (Exception mex) {
        throw new JwmaException("jwma.messagepart.failedcreation", true).setException(mex);
    }
    return partinfo;
}

From source file:com.linkedin.kmf.common.Utils.java

public static String jsonFromGenericRecord(GenericRecord record) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GenericDatumWriter<GenericRecord> writer = new GenericDatumWriter<>(DefaultTopicSchema.MESSAGE_V0);

    try {/*from  w  ww.  j  av  a 2  s.c  o  m*/
        Encoder encoder = new JsonEncoder(DefaultTopicSchema.MESSAGE_V0, out);
        writer.write(record, encoder);
        encoder.flush();
    } catch (IOException e) {
        LOG.error("Unable to serialize avro record due to error " + e);
    }
    return out.toString();
}

From source file:delfos.dataset.util.DatasetPrinter.java

private static String actuallyDoTheTable(final List<Item> itemsAllUsersRated, final List<User> users,
        DatasetLoader<? extends Rating> datasetLoader) {
    List<String> columnNames = new ArrayList<>();
    columnNames.add("user\\items");
    columnNames.addAll(//from w w  w . ja  va 2s  .  c om
            itemsAllUsersRated.stream().map(item -> "Item_" + item.getId()).collect(Collectors.toList()));

    Object[][] data = new Object[users.size()][itemsAllUsersRated.size() + 1];

    DecimalFormat format = new DecimalFormat("0.0000");

    IntStream.range(0, users.size()).forEach(indexUser -> {
        User user = users.get(indexUser);

        data[indexUser][0] = user.toString();

        Map<Integer, ? extends Rating> userRatingsRated = datasetLoader.getRatingsDataset()
                .getUserRatingsRated(user.getId());

        IntStream.range(0, itemsAllUsersRated.size()).forEach(indexItem -> {
            Item item = itemsAllUsersRated.get(indexItem);
            if (userRatingsRated.containsKey(item.getId())) {
                data[indexUser][indexItem + 1] = format
                        .format(userRatingsRated.get(item.getId()).getRatingValue().doubleValue());
            } else {
                data[indexUser][indexItem + 1] = "";
            }
        });
    });

    TextTable textTable = new TextTable(columnNames.toArray(new String[0]), data);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream recordingStream = new PrintStream(baos);
    textTable.printTable(recordingStream, 0);

    return baos.toString();
}

From source file:it.greenvulcano.gvesb.adapter.http.utils.DumpUtils.java

public static void dump(HttpServletResponse response, ByteArrayOutputStream body, StringBuffer log) {

    log.append("-- DUMP HttpServletResponse START").append("\n");
    log.append("Status: ").append(response.getStatus()).append("\n");
    log.append("---- Headers START\n");

    response.getHeaderNames().stream()// w  w  w  . j  a v  a 2 s.co m
            .map(headerName -> "[" + headerName + "]=[" + response.getHeaders(headerName) + "]")
            .forEach(h -> log.append(h));

    log.append("---- Headers END\n");

    log.append("---- Body START\n");
    log.append(body.toString()).append("\n");
    log.append("---- Body END\n");

    log.append("-- DUMP HttpServletResponse END \n");
}

From source file:Main.java

/**
 * Read a file from assets/*  w  ww  . j a  va2 s  .com*/
 *
 * @return the string from assets
 */

public static String getfromAssets(Context ctx, String file_name) {

    AssetManager assetManager = ctx.getAssets();
    ByteArrayOutputStream outputStream = null;
    InputStream inputStream = null;
    try {
        inputStream = assetManager.open(file_name);
        outputStream = new ByteArrayOutputStream();
        byte buf[] = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
        }
    } catch (IOException e) {
    }
    return outputStream.toString();

}

From source file:org.ubicompforall.cityexplorer.CityExplorer.java

/***
 * Ping Google/*  ww w.  j a va 2  s  .  c  om*/
 * Start a browser if the page contains a (log-in) "redirect="
 */
public static boolean pingConnection(Activity context, String url) {
    boolean urlAvailable = false;
    if (ensureConnected(context)) {
        showProgressDialog(context);
        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpResponse response = httpclient.execute(new HttpGet(url));
            StatusLine statusLine = response.getStatusLine();
            debug(2, "statusLine is " + statusLine);

            // HTTP status is OK even if not logged in to NTNU
            //Toast.makeText( context, "Status-line is "+statusLine, Toast.LENGTH_LONG).show();
            if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                String responseString = out.toString();
                if (responseString.contains("redirect=")) { // Connection to url should be checked.
                    debug(2, "Redirect detected for url: " + url);
                    //Toast.makeText( context, "Mismatched url: "+url, Toast.LENGTH_LONG).show();
                } else {
                    urlAvailable = true;
                } // if redirect page, else probably OK
            } else {//if status OK, else: Closes the connection on failure
                response.getEntity().getContent().close();
            } //if httpStatus OK, else close

            //Start browser to log in
            if (!urlAvailable) {
                //throw new IOException( statusLine.getReasonPhrase() );

                //String activity = Thread.currentThread().getStackTrace()[3].getClassName();
                Toast.makeText(context, "Web access needed! Are you logged in?", Toast.LENGTH_LONG).show();
                //Uri uri = Uri.parse( url +"#"+ context.getClass().getCanonicalName() );
                Uri uri = Uri.parse(url + "?activity=" + context.getClass().getCanonicalName());
                debug(0, "Pinging magic url: " + uri);
                debug(0, " Need the web for uri: " + uri);
                context.startActivityForResult(new Intent(Intent.ACTION_VIEW, uri), REQUEST_KILL_BROWSER);
                //urlAvailable=true;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) { // Caused by bad url for example, missing http:// etc. Can still use cached maps...
            urlAvailable = false;
            debug(0, "Missing http:// in " + url + " ?");
        } catch (IOException e) { // e.g. UnknownHostException // try downloading db's from the Web, catch (and print) exceptions
            e.printStackTrace();
            urlAvailable = false;
        }
    } // if not already loaded once before
    return urlAvailable;
}

From source file:com.ikon.util.ExecutionUtils.java

/**
 * Execute script/*from w w  w.  j  av a2s .c  om*/
 * 
 * @return 0 - Return
 *         1 - StdOut
 *         2 - StdErr
 */
public static Object[] runScript(String script) throws EvalError {
    Object[] ret = new Object[3];
    ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(baosOut);
    ByteArrayOutputStream baosErr = new ByteArrayOutputStream();
    PrintStream err = new PrintStream(baosErr);
    Interpreter i = new Interpreter(null, out, err, false);

    ret[0] = i.eval(script);

    out.flush();
    ret[1] = baosOut.toString();

    err.flush();
    ret[2] = baosErr.toString();

    log.debug("runScript: {}", Arrays.toString(ret));
    return ret;
}

From source file:com.ikanow.aleph2.graph.titan.utils.TestMiscTitanProperties.java

protected static String showGraph(final TitanGraph titan) throws IOException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    titan.io(IoCore.graphson()).writer().create().writeGraph(baos, titan);
    return baos.toString();
}