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:fr.cls.atoll.motu.processor.wps.framework.WPSUtils.java

/**
 * Performs an HTTP-Get request and provides typed access to the response.
 * /* w  ww  .j  a va2  s .co m*/
 * @param <T>
 * @param worker
 * @param url
 * @param postBody
 * @param headers
 * @return some object from the url
 * @throws HttpException
 * @throws IOException
 * @throws MotuException 
 */
public static <T> T post(Worker<T> worker, String url, InputStream postBody, Map<String, String> headers)
        throws HttpException, IOException, MotuException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - start");
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();

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

    InputStream postBodyCloned = new ByteArrayInputStream(out.toString().getBytes());

    MultiThreadedHttpConnectionManager connectionManager = HttpUtil.createConnectionManager();
    HttpClientCAS client = new HttpClientCAS(connectionManager);

    HttpClientParams clientParams = new HttpClientParams();
    //clientParams.setParameter("http.protocol.allow-circular-redirects", true); //HttpClientParams.ALLOW_CIRCULAR_REDIRECTS
    client.setParams(clientParams);

    PostMethod post = new PostMethod(url);
    post.getParams().setCookiePolicy(CookiePolicy.RFC_2109);

    InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(postBody);
    post.setRequestEntity(inputStreamRequestEntity);
    for (String key : headers.keySet()) {
        post.setRequestHeader(key, headers.get(key));
    }

    String query = post.getQueryString();

    // Check redirection
    // DONT USE post.setFollowRedirects(true); see http://hc.apache.org/httpclient-3.x/redirects.html

    int httpReturnCode = client.executeMethod(post);
    if (LOG.isDebugEnabled()) {
        String msg = String.format("Executing the query:\n==> http code: '%d':\n==> url: '%s'\n==> body:\n'%s'",
                httpReturnCode, url, query);
        LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end - " + msg);
    }

    if (httpReturnCode == 302) {
        post.releaseConnection();
        String redirectLocation = null;
        Header locationHeader = post.getResponseHeader("location");

        if (locationHeader != null) {
            redirectLocation = locationHeader.getValue();
            if (!WPSUtils.isNullOrEmpty(redirectLocation)) {
                if (LOG.isDebugEnabled()) {
                    String msg = String.format("Query is redirected to url: '%s'", redirectLocation);
                    LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end - " + msg);
                }
                post = new PostMethod(url);
                post.setRequestEntity(new InputStreamRequestEntity(postBodyCloned)); // Recrire un nouveau InputStream
                for (String key : headers.keySet()) {
                    post.setRequestHeader(key, headers.get(key));
                }

                clientParams.setBooleanParameter(HttpClientCAS.ADD_CAS_TICKET_PARAM, false);
                httpReturnCode = client.executeMethod(post);
                clientParams.setBooleanParameter(HttpClientCAS.ADD_CAS_TICKET_PARAM, true);

                if (LOG.isDebugEnabled()) {
                    String msg = String.format(
                            "Executing the query:\n==> http code: '%d':\n==> url: '%s'\n==> body:\n'%s'",
                            httpReturnCode, url, query);
                    LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end - " + msg);
                }

            }

        }
    }

    T returnValue = worker.work(post.getResponseBodyAsStream());

    if (httpReturnCode >= 400) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end");
        }

        String msg = String.format(
                "Error while executing the query:\n==> http code: '%d':\n==> url: '%s'\n==> body:\n'%s'",
                httpReturnCode, url, query);
        throw new MotuException(msg);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end");
    }
    return returnValue;
}

From source file:com.cloudbees.hudson.plugins.folder.computed.ComputedFolderTest.java

static String doRecompute(ComputedFolder<?> d, Result result) throws Exception {
    d.scheduleBuild2(0).getFuture().get();
    FolderComputation<?> computation = d.getComputation();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    computation.writeWholeLogTo(baos);/*from  ww  w . j  a v  a 2  s  . c  o  m*/
    String log = baos.toString();
    assertEquals(log, result, computation.getResult());
    return log;
}

From source file:com.roamtouch.menuserver.utils.FileUtils.java

/**
 * Read a text file into a String, optionally limiting the length.
 * @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
 *///from  w w  w  .j ava2s.c o  m
public static String readTextFile(File file, int max, String ellipsis) throws IOException {
    InputStream input = new FileInputStream(file);
    try {
        if (max > 0) { // "head" mode: read the first N bytes
            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: read it all, 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: read it all
            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:com.apptentive.android.sdk.comm.ApptentiveClient.java

private static ApptentiveHttpResponse performMultipartFilePost(Context context, String oauthToken, String uri,
        String postBody, StoredFile storedFile) {
    Log.d("Performing multipart request to %s", uri);

    ApptentiveHttpResponse ret = new ApptentiveHttpResponse();

    if (storedFile == null) {
        Log.e("StoredFile is null. Unable to send.");
        return ret;
    }/*from  w  w w . ja  va2s.  com*/

    int bytesRead;
    int bufferSize = 4096;
    byte[] buffer;

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = UUID.randomUUID().toString();

    HttpURLConnection connection;
    DataOutputStream os = null;
    InputStream is = null;

    try {
        is = context.openFileInput(storedFile.getLocalFilePath());

        // Set up the request.
        URL url = new URL(uri);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setConnectTimeout(DEFAULT_HTTP_CONNECT_TIMEOUT);
        connection.setReadTimeout(DEFAULT_HTTP_SOCKET_TIMEOUT);
        connection.setRequestMethod("POST");

        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        connection.setRequestProperty("Authorization", "OAuth " + oauthToken);
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("X-API-Version", API_VERSION);
        connection.setRequestProperty("User-Agent", getUserAgentString());

        StringBuilder requestText = new StringBuilder();

        // Write form data
        requestText.append(twoHyphens).append(boundary).append(lineEnd);
        requestText.append("Content-Disposition: form-data; name=\"message\"").append(lineEnd);
        requestText.append("Content-Type: text/plain").append(lineEnd);
        requestText.append(lineEnd);
        requestText.append(postBody);
        requestText.append(lineEnd);

        // Write file attributes.
        requestText.append(twoHyphens).append(boundary).append(lineEnd);
        requestText.append(String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"",
                storedFile.getFileName())).append(lineEnd);
        requestText.append("Content-Type: ").append(storedFile.getMimeType()).append(lineEnd);
        requestText.append(lineEnd);

        Log.d("Post body: " + requestText);

        // Open an output stream.
        os = new DataOutputStream(connection.getOutputStream());

        // Write the text so far.
        os.writeBytes(requestText.toString());

        try {
            // Write the actual file.
            buffer = new byte[bufferSize];
            while ((bytesRead = is.read(buffer, 0, bufferSize)) > 0) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            Log.d("Error writing file bytes to HTTP connection.", e);
            ret.setBadPayload(true);
            throw e;
        }

        os.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        os.close();

        ret.setCode(connection.getResponseCode());
        ret.setReason(connection.getResponseMessage());

        // TODO: These streams may not be ready to read now. Put this in a new thread.
        // Read the normal response.
        InputStream nis = null;
        ByteArrayOutputStream nbaos = null;
        try {
            Log.d("Sending file: " + storedFile.getLocalFilePath());
            nis = connection.getInputStream();
            nbaos = new ByteArrayOutputStream();
            byte[] eBuf = new byte[1024];
            int eRead;
            while (nis != null && (eRead = nis.read(eBuf, 0, 1024)) > 0) {
                nbaos.write(eBuf, 0, eRead);
            }
            ret.setContent(nbaos.toString());
        } catch (IOException e) {
            Log.w("Can't read return stream.", e);
        } finally {
            Util.ensureClosed(nis);
            Util.ensureClosed(nbaos);
        }

        // Read the error response.
        InputStream eis = null;
        ByteArrayOutputStream ebaos = null;
        try {
            eis = connection.getErrorStream();
            ebaos = new ByteArrayOutputStream();
            byte[] eBuf = new byte[1024];
            int eRead;
            while (eis != null && (eRead = eis.read(eBuf, 0, 1024)) > 0) {
                ebaos.write(eBuf, 0, eRead);
            }
            if (ebaos.size() > 0) {
                ret.setContent(ebaos.toString());
            }
        } catch (IOException e) {
            Log.w("Can't read error stream.", e);
        } finally {
            Util.ensureClosed(eis);
            Util.ensureClosed(ebaos);
        }

        Log.d("HTTP " + connection.getResponseCode() + ": " + connection.getResponseMessage() + "");
        Log.v(ret.getContent());
    } catch (FileNotFoundException e) {
        Log.e("Error getting file to upload.", e);
    } catch (MalformedURLException e) {
        Log.e("Error constructing url for file upload.", e);
    } catch (SocketTimeoutException e) {
        Log.w("Timeout communicating with server.");
    } catch (IOException e) {
        Log.e("Error executing file upload.", e);
    } finally {
        Util.ensureClosed(is);
        Util.ensureClosed(os);
    }
    return ret;
}

From source file:hudson.plugins.android_emulator.SdkInstaller.java

private static boolean isPlatformInstalled(PrintStream logger, Launcher launcher, AndroidSdk sdk,
        String platform, String abi) throws IOException, InterruptedException {
    ByteArrayOutputStream targetList = new ByteArrayOutputStream();
    // Preferably we'd use the "--compact" flag here, but it wasn't added until r12,
    // nor does it give any information about which system images are installed...
    Utils.runAndroidTool(launcher, targetList, logger, sdk, Tool.ANDROID, "list target", null);
    boolean platformInstalled = targetList.toString().contains('"' + platform + '"');
    if (!platformInstalled) {
        return false;
    }//from w w  w .  ja  va  2  s  . c  om

    if (abi != null) {
        // Check whether the desired ABI is included in the output
        Pattern regex = Pattern.compile(String.format("\"%s\".+?%s", platform, abi), Pattern.DOTALL);
        Matcher matcher = regex.matcher(targetList.toString());
        if (!matcher.find() || matcher.group(0).contains("---")) {
            // We did not find the desired ABI within the section for the given platform
            return false;
        }
    }

    // Everything we wanted is installed
    return true;
}

From source file:airlift.util.AirliftUtil.java

/**
 * Serialize stack trace./*w  w  w  .  j  ava  2s.  c  o m*/
 *
 * @param _t the _t
 * @return the string
 */
public static String serializeStackTrace(Throwable _t) {
    java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream();
    java.io.PrintWriter printWriter = null;
    String errorString = null;

    try {
        printWriter = new java.io.PrintWriter(byteArrayOutputStream, true);
        _t.printStackTrace(printWriter);
        errorString = byteArrayOutputStream.toString();
    } catch (Throwable u) {
        if (printWriter != null) {
            try {
                printWriter.close();
            } catch (Throwable v) {
            }
        }
    }

    return errorString;
}

From source file:org.vuphone.assassins.android.http.HTTPGetter.java

private static HashMap<String, Double> handleGameAreaResponse(HttpGet get) {

    HttpResponse resp;/*from w w  w . j  a v  a 2s .  c o  m*/

    // Execute the get
    try {
        resp = c.execute(get);
    } catch (ClientProtocolException e1) {
        e1.printStackTrace();
        Log.e(VUphone.tag, pre + "HTTP error while executing post");
        return null;
    } catch (SocketException se) {
        // If we have no Internet connection, we don't want to wipe the
        // existing list of land mines by returning null.
        Log.e(VUphone.tag, pre + "SocketException: Invalid Internet " + "Connection");
        se.printStackTrace();
        return null;
    } catch (IOException e1) {
        e1.printStackTrace();
        Log.e(VUphone.tag, pre + "HTTP error in server response");
        return null;
    } catch (Exception e) {
        Log.e(VUphone.tag, pre + "An unknown exception was thrown");
        e.printStackTrace();
        return null;
    }

    Log.i(VUphone.tag, pre + "HTTP operation complete. Processing response.");

    // Convert Response Entity to usable format
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    try {
        resp.getEntity().writeTo(bao);
        Log.v(VUphone.tag, pre + "Http response: " + bao);
    } catch (IOException e) {
        e.printStackTrace();
        Log.e(VUphone.tag, pre + "Unable to write response to byte[]");
        return null;
    }

    if (bao.size() == 0) {
        Log.w(VUphone.tag,
                pre + "Response was completely empty, " + "are you sure you are using the "
                        + "same version client and server? " + "At the least, there should have "
                        + "been empty XML here");
    }

    HashMap<String, Double> data = new HashMap<String, Double>();

    String response = bao.toString();
    String[] vals = response.split("&");
    for (int i = 0; i < vals.length; i++) {
        String[] val = vals[i].split("=");
        data.put(val[0], Double.valueOf(val[1]));
    }

    return data;
}

From source file:com.android.mms.service.http.NetworkAwareHttpClient.java

/**
 * Generates a cURL command equivalent to the given request.
 *//*ww w  .  j a  v  a 2  s . c  o  m*/
private static String toCurl(HttpUriRequest request, boolean logAuthToken) throws IOException {
    StringBuilder builder = new StringBuilder();

    builder.append("curl ");

    // add in the method
    builder.append("-X ");
    builder.append(request.getMethod());
    builder.append(" ");

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

                if (isBinaryContent(request)) {
                    String base64 = Base64.encodeToString(stream.toByteArray(), Base64.NO_WRAP);
                    builder.insert(0, "echo '" + base64 + "' | base64 -d > /tmp/$$.bin; ");
                    builder.append(" --data-binary @/tmp/$$.bin");
                } else {
                    String entityString = stream.toString();
                    builder.append(" --data-ascii \"").append(entityString).append("\"");
                }
            } else {
                builder.append(" [TOO MUCH DATA TO INCLUDE]");
            }
        }
    }

    return builder.toString();
}

From source file:com.xhsoft.framework.common.utils.ClassUtil.java

/**
 * //  w  w w . jav  a 2  s . c  o m
 * @return - String
 * @author: lizj
 */
public static String getCallerName(int depth) {
    String JDK_VERSION = System.getProperty("java.version");

    double version = 1.3D;

    try {
        JDK_VERSION = JDK_VERSION.substring(0, 3);

        version = Double.parseDouble(JDK_VERSION);
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }

    if (DEBUG) {
        log.debug("java.version: " + version);
    }

    if (version >= 1.5D) {
        try {
            Thread currentThread = Thread.currentThread();

            StackTraceElement[] stack = (StackTraceElement[]) (Thread.class
                    .getMethod("getStackTrace", new Class[0]).invoke(currentThread, new Object[0]));

            if (stack != null && stack.length >= 3) {
                for (int i = 0; i < stack.length; i++) {
                    if (stack[i].getClassName().equals(ClassUtil.class.getName())
                            && "getCallerName".equals(stack[i].getMethodName())) {
                        if (i + 2 + depth < stack.length) {
                            return stack[i + 2 + depth].getClassName() + "."
                                    + stack[i + 2 + depth].getMethodName();
                        }
                    }
                }

                return null;
            }
        } catch (IllegalArgumentException e1) {
            e1.printStackTrace();
        } catch (SecurityException e1) {
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
        } catch (InvocationTargetException e1) {
            e1.printStackTrace();
        } catch (NoSuchMethodException e1) {
            e1.printStackTrace();
        }
    } else if (version >= 1.4D) {
        StackTraceElement[] stack = (new Throwable()).getStackTrace();

        if (stack != null && stack.length >= (3 + depth)) {
            return stack[2 + depth].getClassName() + "." + stack[2 + depth].getMethodName();
        }
    }

    java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream(4096);

    new Throwable().printStackTrace(new java.io.PrintStream(bos));

    String x = bos.toString();

    java.io.BufferedReader br = new java.io.BufferedReader(new java.io.StringReader(x));

    String val = null;
    String str = null;

    try {
        int i = 0;

        while ((str = br.readLine()) != null) {
            if (i++ == (3 + depth)) {
                str = StringUtil.getA5(str, "at ");

                val = str = StringUtil.getB4(str, "(");
            }
        }
    } catch (IOException e) {
    }

    return val;
}

From source file:latexstudio.editor.runtime.CommandLineExecutor.java

public static synchronized void executeGeneratePDF(CommandLineBuilder cmd) {
    String outputDirectory = "--output-directory=" + cmd.getOutputDirectory();
    String outputFormat = "--output-format=pdf";
    String job = cmd.getJobname() == null ? "" : "--jobname=" + cmd.getJobname().replaceAll(" ", "_");
    ByteArrayOutputStream outputStream = null;

    try {//from ww w .j  a va2  s .  c  om
        String[] command = new String[] { outputDirectory, outputFormat, job, cmd.getPathToSource() };

        CommandLine cmdLine = new CommandLine(ApplicationUtils.getPathToTEX(cmd.getLatexPath()));
        //For windows, we set handling quoting to true
        cmdLine.addArguments(command, ApplicationUtils.isWindows());

        outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        EXECUTOR.setStreamHandler(streamHandler);

        if (cmd.getWorkingFile() != null) {
            EXECUTOR.setWorkingDirectory(cmd.getWorkingFile().getParentFile().getAbsoluteFile());
        }

        EXECUTOR.execute(cmdLine);

        if (cmd.getLogger() != null) {
            cmd.getLogger().log(cmdLine.toString());
            cmd.getLogger().log(outputStream.toString());
        }

    } catch (IOException e) {
        if (cmd.getLogger() != null) {
            cmd.getLogger().log("The path to the pdflatex tool is incorrect or has not been set.");
        }
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}