Example usage for java.io PrintWriter append

List of usage examples for java.io PrintWriter append

Introduction

In this page you can find the example usage for java.io PrintWriter append.

Prototype

public PrintWriter append(char c) 

Source Link

Document

Appends the specified character to this writer.

Usage

From source file:edu.stanford.epad.epadws.handlers.HandlerUtil.java

public static int infoResponse(int responseCode, String message, PrintWriter responseStream, EPADLogger log) {
    log.info(message);//from  ww w  .  j a va2  s.  com
    if (responseStream != null)
        responseStream.append(message);
    return responseCode;
}

From source file:rapture.common.exception.ExceptionToString.java

public static final String format(Throwable toss) {
    StringWriter sw = new StringWriter();

    // Improved nested exception handling
    PrintWriter pw = new PrintWriter(sw) {
        boolean stop = false;

        @Override//from   w  w w . j a  va  2s .c o m
        public void print(String s) {
            if (s.startsWith("Caused by"))
                stop = true;
            else if (!s.startsWith(" ") && !s.startsWith("\t"))
                stop = false;
            if (!stop)
                super.print(s);
        }

        @Override
        public void println() {
            if (!stop)
                super.println();
        }

    };
    for (Throwable t = toss; t != null;) {
        t.printStackTrace(pw);
        t = t.getCause();
        if (t != null)
            pw.append("Caused by: ");
    }
    return sw.toString();
}

From source file:edu.stanford.epad.epadws.handlers.HandlerUtil.java

public static int warningJSONResponse(int responseCode, String message, PrintWriter responseStream,
        EPADLogger log) {/*  w  w  w.  j a v  a 2s.c  o  m*/
    if (responseStream != null) {
        message = new EPADMessage(message).toJSON();
        log.warning("Message to client:" + message);
        responseStream.append(message);
    } else
        log.warning(message);
    return responseCode;
}

From source file:com.androidex.volley.toolbox.HurlStack.java

/**
 * Perform a multipart request on a connection
 * //  w w  w . j a v  a  2s .c o m
 * @param connection
 *            The Connection to perform the multi part request
 * @param request
 *            The params to add to the Multi Part request
 *            The files to upload
 * @throws ProtocolException
 */
private static void setConnectionParametersForMultipartRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, ProtocolException {

    final String charset = ((MultiPartRequest<?>) request).getProtocolCharset();
    final int curTime = (int) (System.currentTimeMillis() / 1000);
    final String boundary = BOUNDARY_PREFIX + curTime;
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setRequestProperty(HEADER_CONTENT_TYPE, String.format(CONTENT_TYPE_MULTIPART, charset, curTime));

    Map<String, MultiPartParam> multipartParams = ((MultiPartRequest<?>) request).getMultipartParams();
    Map<String, String> filesToUpload = ((MultiPartRequest<?>) request).getFilesToUpload();

    if (((MultiPartRequest<?>) request).isFixedStreamingMode()) {
        int contentLength = getContentLengthForMultipartRequest(boundary, multipartParams, filesToUpload);

        connection.setFixedLengthStreamingMode(contentLength);
    } else {
        connection.setChunkedStreamingMode(0);
    }
    // Modified end

    ProgressListener progressListener;
    progressListener = (ProgressListener) request;

    PrintWriter writer = null;
    try {
        OutputStream out = connection.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(out, charset), true);

        for (String key : multipartParams.keySet()) {
            MultiPartParam param = multipartParams.get(key);

            writer.append(boundary).append(CRLF)
                    .append(String.format(HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA, key))
                    .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + param.contentType).append(CRLF)
                    .append(CRLF).append(param.value).append(CRLF).flush();
        }

        for (String key : filesToUpload.keySet()) {

            File file = new File(filesToUpload.get(key));

            if (!file.exists()) {
                throw new IOException(String.format("File not found: %s", file.getAbsolutePath()));
            }

            if (file.isDirectory()) {
                throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath()));
            }

            writer.append(boundary).append(CRLF)
                    .append(String.format(
                            HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA + SEMICOLON_SPACE + FILENAME,
                            key, file.getName()))
                    .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + CONTENT_TYPE_OCTET_STREAM)
                    .append(CRLF).append(HEADER_CONTENT_TRANSFER_ENCODING + COLON_SPACE + BINARY).append(CRLF)
                    .append(CRLF).flush();

            BufferedInputStream input = null;
            try {
                FileInputStream fis = new FileInputStream(file);
                int transferredBytes = 0;
                int totalSize = (int) file.length();
                input = new BufferedInputStream(fis);
                int bufferLength = 0;

                byte[] buffer = new byte[1024];
                while ((bufferLength = input.read(buffer)) > 0) {
                    out.write(buffer, 0, bufferLength);
                    transferredBytes += bufferLength;
                    progressListener.onProgress(transferredBytes, totalSize);
                }
                out.flush(); // Important! Output cannot be closed. Close of
                             // writer will close
                             // output as well.
            } finally {
                if (input != null)
                    try {
                        input.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
            }
            writer.append(CRLF).flush(); // CRLF is important! It indicates
            // end of binary
            // boundary.
        }

        // End of multipart/form-data.
        writer.append(boundary + BOUNDARY_PREFIX).append(CRLF).flush();

    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:edu.stanford.epad.epadws.handlers.HandlerUtil.java

public static int infoJSONResponse(int responseCode, String message, PrintWriter responseStream,
        EPADLogger log) {//from   www . j  av  a 2 s.c o m
    log.info(message);
    if (responseStream != null) {
        message = new EPADMessage(message, Level.INFO).toJSON();
        log.info("Message to client:" + message);
        responseStream.append(message);
    }
    return responseCode;
}

From source file:edu.stanford.epad.epadws.handlers.HandlerUtil.java

public static int warningJSONResponse(int responseCode, String message, Throwable t, PrintWriter responseStream,
        EPADLogger log) {/*from w  w  w.  j a v  a  2  s  . c o  m*/
    String finalMessage = message + (t == null ? "" : ((t.getMessage() == null) ? "" : ": " + t.getMessage()));
    log.warning(finalMessage, t);
    if (responseStream != null)
        responseStream.append(new EPADMessage(finalMessage).toJSON());
    return responseCode;
}

From source file:edu.stanford.epad.epadws.handlers.HandlerUtil.java

public static int warningResponse(int responseCode, String message, PrintWriter responseStream,
        EPADLogger log) {/* ww w . j  a  v a 2 s .  c  om*/
    if (responseStream != null) {
        if (!message.startsWith("{"))
            message = new EPADMessage(message).toJSON();
        log.warning("Message to client:" + message);
        responseStream.append(message);
    } else
        log.warning(message);
    return responseCode;
}

From source file:com.volley.air.toolbox.HurlStack.java

/**
 * Perform a multipart request on a connection
 * //from   w  w w.ja v a2s  . c  o  m
 * @param connection
 *            The Connection to perform the multi part request
 * @param request
 *            The params to add to the Multi Part request
 *            The files to upload
 * @throws ProtocolException
 */
private static void setConnectionParametersForMultipartRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, ProtocolException {

    final String charset = ((MultiPartRequest<?>) request).getProtocolCharset();
    final int curTime = (int) (System.currentTimeMillis() / 1000);
    final String boundary = BOUNDARY_PREFIX + curTime;
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setRequestProperty(HEADER_CONTENT_TYPE, String.format(CONTENT_TYPE_MULTIPART, charset, curTime));

    Map<String, MultiPartParam> multipartParams = ((MultiPartRequest<?>) request).getMultipartParams();
    Map<String, String> filesToUpload = ((MultiPartRequest<?>) request).getFilesToUpload();

    if (((MultiPartRequest<?>) request).isFixedStreamingMode()) {
        int contentLength = getContentLengthForMultipartRequest(boundary, multipartParams, filesToUpload);

        connection.setFixedLengthStreamingMode(contentLength);
    } else {
        connection.setChunkedStreamingMode(0);
    }
    // Modified end

    ProgressListener progressListener;
    progressListener = (ProgressListener) request;

    PrintWriter writer = null;
    try {
        OutputStream out = connection.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(out, charset), true);

        for (Entry<String, MultiPartParam> entry : multipartParams.entrySet()) {
            MultiPartParam param = entry.getValue();

            writer.append(boundary).append(CRLF)
                    .append(String.format(HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA, entry.getKey()))
                    .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + param.contentType).append(CRLF)
                    .append(CRLF).append(param.value).append(CRLF).flush();
        }

        for (Entry<String, String> entry : filesToUpload.entrySet()) {

            File file = new File(entry.getValue());

            if (!file.exists()) {
                throw new IOException(String.format("File not found: %s", file.getAbsolutePath()));
            }

            if (file.isDirectory()) {
                throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath()));
            }

            writer.append(boundary).append(CRLF)
                    .append(String.format(
                            HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA + SEMICOLON_SPACE + FILENAME,
                            entry.getKey(), file.getName()))
                    .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + CONTENT_TYPE_OCTET_STREAM)
                    .append(CRLF).append(HEADER_CONTENT_TRANSFER_ENCODING + COLON_SPACE + BINARY).append(CRLF)
                    .append(CRLF).flush();

            BufferedInputStream input = null;
            try {
                FileInputStream fis = new FileInputStream(file);
                int transferredBytes = 0;
                int totalSize = (int) file.length();
                input = new BufferedInputStream(fis);
                int bufferLength;

                byte[] buffer = new byte[1024];
                while ((bufferLength = input.read(buffer)) > 0) {
                    out.write(buffer, 0, bufferLength);
                    transferredBytes += bufferLength;
                    progressListener.onProgress(transferredBytes, totalSize);
                }
                out.flush(); // Important! Output cannot be closed. Close of
                             // writer will close
                             // output as well.
            } finally {
                if (input != null)
                    try {
                        input.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
            }
            writer.append(CRLF).flush(); // CRLF is important! It indicates
            // end of binary
            // boundary.
        }

        // End of multipart/form-data.
        writer.append(boundary + BOUNDARY_PREFIX).append(CRLF).flush();

    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:org.apache.openejb.cli.MainImpl.java

private static void help(final boolean printHeader) {

    // Here we are using commons-cli to create the list of available commands
    // We actually use a different Options object to parse the 'openejb' command
    try {//from  www .j a va 2s .  c  o  m
        final Options options = new Options();

        final ResourceFinder commandFinder = new ResourceFinder("META-INF");
        final Map<String, Properties> commands = commandFinder.mapAvailableProperties("org.apache.openejb.cli");
        for (final Map.Entry<String, Properties> command : commands.entrySet()) {
            if (command.getKey().contains(".")) {
                continue;
            }
            final Properties p = command.getValue();
            final String description = p.getProperty(descriptionI18n, p.getProperty(descriptionBase));
            options.addOption(command.getKey(), false, description);
        }

        final HelpFormatter formatter = new HelpFormatter();
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw);

        final String syntax = "openejb <command> [options] [args]";

        final String header = "\nAvailable commands:";

        final String footer = "\n" + "Try 'openejb <command> --help' for help on a specific command.\n"
                + "For example 'openejb deploy --help'.\n" + "\n"
                + "Apache OpenEJB -- EJB Container System and Server.\n"
                + "For additional information, see http://tomee.apache.org\n"
                + "Bug Reports to <users@tomee.apache.org>";

        if (!printHeader) {
            pw.append(header).append("\n\n");
            formatter.printOptions(pw, 74, options, 1, 3);
        } else {
            formatter.printHelp(pw, 74, syntax, header, options, 1, 3, footer, false);
        }

        pw.flush();

        // Fix up the commons-cli output to our liking.
        String text = sw.toString().replaceAll("\n -", "\n  ");
        text = text.replace("\nApache OpenEJB", "\n\nApache OpenEJB");
        System.out.print(text);
    } catch (final IOException e) {
        e.printStackTrace();
    }
}

From source file:edu.stanford.epad.epadws.handlers.HandlerUtil.java

public static int warningResponse(int responseCode, String message, Throwable t, PrintWriter responseStream,
        EPADLogger log) {/*from  w w  w .ja  va  2  s  . c  o m*/
    String finalMessage = message + (t == null ? "" : ((t.getMessage() == null) ? "" : ": " + t.getMessage()));
    if (responseStream != null) {
        finalMessage = new EPADMessage(finalMessage).toJSON();
        responseStream.append(finalMessage);
    } else
        log.warning(finalMessage);
    return responseCode;
}