Example usage for java.io PrintWriter print

List of usage examples for java.io PrintWriter print

Introduction

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

Prototype

public void print(Object obj) 

Source Link

Document

Prints an object.

Usage

From source file:com.sat.common.CustomReport.java

/**
 * Generate html file.//from w w  w  . j a  v  a 2  s.c  om
 *
 * @param msg the msg
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws FileNotFoundException the file not found exception
 */
private static void generateHtmlFile(String msg) throws IOException, FileNotFoundException {
    String htmlfname = "./customreport.html";
    String eol = System.getProperty("line.separator");
    msg = msg.replaceAll("<tr", eol + "<tr");
    msg = msg.replaceAll("</table>", eol + "</table>");
    msg = msg.replaceAll("<table", eol + "<table");
    new FileOutputStream(htmlfname).close();
    PrintWriter htmlfile = new PrintWriter(new BufferedWriter(new FileWriter(htmlfname, true)));
    htmlfile.print(msg);
    htmlfile.close();
}

From source file:com.amazonaws.eclipse.core.diagnostic.utils.AwsPortalFeedbackFormUtils.java

/**
 * Serialize the specified error report data into "x-www-form-urlencoded"
 * format. This method also appends additional parameters that are
 * implicitly required by the Amazon HTMLForms system (including
 * authenticity_token).//from  ww w. j av a  2 s. co  m
 */
private static String generateFormPostContent(final ErrorReportDataModel reportData,
        final String authentityToken) {
    StringBuilder content = new StringBuilder();

    // These are the additional fields required by the POST API
    content.append(AUTHENTICITY_TOKEN).append("=").append(SdkHttpUtils.urlEncode(authentityToken, false));
    content.append("&_method=put");

    // These are the "real" data fields

    /* ============= User email ============= */
    content.append("&");
    content.append(FORM_FIELD_PREFIX).append(EMAIL).append("=");
    content.append(SdkHttpUtils.urlEncode(reportData.getUserEmail(), false));

    /* ============= User description of the error ============= */
    content.append("&");
    content.append(FORM_FIELD_PREFIX).append(USER_DESCRIPTION).append("=");
    content.append(SdkHttpUtils.urlEncode(reportData.getUserDescription(), false));

    /* ============= Error stack trace ============= */
    content.append("&");
    content.append(FORM_FIELD_PREFIX).append(ERROR_STACKTRACE).append("=");
    content.append(SdkHttpUtils.urlEncode(getStackTraceFromThrowable(reportData.getBug()), false));

    /* ============= Error status message ============= */
    content.append("&");
    content.append(FORM_FIELD_PREFIX).append(ERROR_STATUS_MESSAGE).append("=");
    content.append(SdkHttpUtils.urlEncode(reportData.getStatusMessage(), false));

    PlatformEnvironmentDataModel env = reportData.getPlatformEnv();

    /* ============= Platform environment ============= */
    content.append("&");
    content.append(FORM_FIELD_PREFIX).append(ECLIPSE_PLATFORM_ENV).append("=");

    if (env != null) {
        StringWriter eclipsePlatformEnv = new StringWriter();
        PrintWriter pw = new PrintWriter(eclipsePlatformEnv);
        pw.print("Eclipse platform version : ");
        pw.println(env.getEclipsePlatformVersion());

        pw.print("OS name : ");
        pw.println(env.getOsName());
        pw.print("OS version : ");
        pw.println(env.getOsVersion());
        pw.print("OS architecture : ");
        pw.println(env.getOsArch());
        pw.print("JVM name : ");
        pw.println(env.getJavaVmName());
        pw.print("JVM version : ");
        pw.println(env.getJavaVmVersion());
        pw.print("Java lang version : ");
        pw.println(env.getJavaVersion());
        pw.println();
        pw.println();

        content.append(SdkHttpUtils.urlEncode(eclipsePlatformEnv.toString(), false));
    }

    /* ============= Installed Plug-ins ============= */
    content.append("&");
    content.append(FORM_FIELD_PREFIX).append(INSTALLED_PLUGINS).append("=");

    if (env != null) {
        StringWriter installedPlugins = new StringWriter();
        PrintWriter pw = new PrintWriter(installedPlugins);

        for (Bundle bundle : env.getInstalledBundles()) {
            pw.println(bundle.toString());
        }

        content.append(SdkHttpUtils.urlEncode(installedPlugins.toString(), false));
    }

    return content.toString();
}

From source file:org.rapidoid.http.HttpClientUtil.java

private static HttpResp response(HttpResponse response) throws IOException {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintWriter printer = new PrintWriter(baos);

    printer.print(response.getStatusLine() + "");
    printer.print("\n");

    Map<String, String> headers = U.map();

    for (Header hdr : response.getAllHeaders()) {
        printer.print(hdr.getName());//from   w  ww .  j a va 2 s  . c om
        printer.print(": ");
        printer.print(hdr.getValue());
        printer.print("\n");

        headers.put(hdr.getName(), hdr.getValue());
    }

    printer.print("\n");
    printer.flush();

    HttpEntity entity = response.getEntity();
    byte[] body = entity != null ? IO.loadBytes(response.getEntity().getContent()) : new byte[0];

    baos.write(body);
    byte[] raw = baos.toByteArray();

    return new HttpResp(raw, response.getStatusLine().getStatusCode(), headers, body);
}

From source file:PostTest.java

/**
 * Makes a POST request and returns the server response.
 * @param urlString the URL to post to/*w  w w . j  a  va2  s . c  o  m*/
 * @param nameValuePairs a map of name/value pairs to supply in the request.
 * @return the server reply (either from the input stream or the error stream)
 */
public static String doPost(String urlString, Map<String, String> nameValuePairs) throws IOException {
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);

    PrintWriter out = new PrintWriter(connection.getOutputStream());

    boolean first = true;
    for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) {
        if (first)
            first = false;
        else
            out.print('&');
        String name = pair.getKey();
        String value = pair.getValue();
        out.print(name);
        out.print('=');
        out.print(URLEncoder.encode(value, "UTF-8"));
    }

    out.close();

    Scanner in;
    StringBuilder response = new StringBuilder();
    try {
        in = new Scanner(connection.getInputStream());
    } catch (IOException e) {
        if (!(connection instanceof HttpURLConnection))
            throw e;
        InputStream err = ((HttpURLConnection) connection).getErrorStream();
        if (err == null)
            throw e;
        in = new Scanner(err);
    }

    while (in.hasNextLine()) {
        response.append(in.nextLine());
        response.append("\n");
    }

    in.close();
    return response.toString();
}

From source file:com.vmware.identity.openidconnect.server.Shared.java

public static void writeJSONResponse(HttpServletResponse httpServletResponse, int statusCode,
        JSONObject jsonObject) throws IOException {
    Validate.notNull(httpServletResponse, "httpServletResponse");
    Validate.notNull(jsonObject, "jsonObject");

    PrintWriter writer = null;
    try {/*from  w  w  w.j a  v a2 s .co m*/
        httpServletResponse.setStatus(statusCode);
        httpServletResponse.setContentType("application/json");
        writer = httpServletResponse.getWriter();
        writer.print(jsonObject.toString());
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:baggage.hypertoolkit.html.Html.java

public static Renderable nbsp() {
    return new Renderable() {
        public void render(PrintWriter printWriter) throws IOException {
            printWriter.print("&nbsp;");
        }//ww w  . j  a  v  a2s.c  o m
    };
}

From source file:com.linecorp.armeria.server.ServerTest.java

private static void testSimple(String reqLine, String expectedStatusLine, String... expectedHeaders)
        throws Exception {

    try (Socket socket = new Socket()) {
        socket.setSoTimeout((int) (idleTimeoutMillis * 4));
        socket.connect(server().activePort().get().localAddress());
        PrintWriter outWriter = new PrintWriter(socket.getOutputStream(), false);

        outWriter.print(reqLine);
        outWriter.print("\r\n");
        outWriter.print("Connection: close\r\n");
        outWriter.print("Content-Length: 0\r\n");
        outWriter.print("\r\n");
        outWriter.flush();//  www . j  a v  a  2s  . c o  m

        BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), StandardCharsets.US_ASCII));

        assertThat(in.readLine(), is(expectedStatusLine));
        // Read till the end of the connection.
        List<String> headers = new ArrayList<>();
        for (;;) {
            String line = in.readLine();
            if (line == null) {
                break;
            }

            // This is not really correct, but just wanna make it as simple as possible.
            headers.add(line);
        }

        for (String expectedHeader : expectedHeaders) {
            if (!headers.contains(expectedHeader)) {
                fail("does not contain '" + expectedHeader + "': " + headers);
            }
        }
    }
}

From source file:com.espertech.esper.antlr.ASTUtil.java

/**
 * Print the token stream to the logger.
 * @param tokens to print//from   w  ww .  j  a  v a  2s  .c  o m
 */
public static void printTokens(CommonTokenStream tokens) {
    if (log.isDebugEnabled()) {
        List tokenList = tokens.getTokens();

        StringWriter writer = new StringWriter();
        PrintWriter printer = new PrintWriter(writer);
        for (int i = 0; i < tokens.size(); i++) {
            Token t = (Token) tokenList.get(i);
            String text = t.getText();
            if (text.trim().length() == 0) {
                printer.print("'" + text + "'");
            } else {
                printer.print(text);
            }
            printer.print('[');
            printer.print(t.getType());
            printer.print(']');
            printer.print(" ");
        }
        printer.println();
        log.debug("Tokens: " + writer.toString());
    }
}

From source file:IO.java

public static void writeData(int[] data, int nData, String filepath) {
    File file = new File(filepath);
    PrintWriter writer;

    try {//from   w  ww.  j av  a  2s .com

        writer = new PrintWriter(file);
        for (int i = 0; i < nData; i++) {
            if (i == nData - 1) {
                writer.print(data[i]);
            } else {
                writer.print(data[i] + ",");
            }
        }
        writer.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:mx.unam.ecologia.gye.coalescence.app.CreateMicsatInput.java

protected static final void writeMicsat(List leaves, String fname) {
    try {/*ww  w . ja v  a  2 s . c o  m*/

        FileOutputStream fout = new FileOutputStream(fname);
        PrintWriter pw = new PrintWriter(fout);
        for (int i = 0; i < leaves.size(); i++) {
            UniParentalGene upgene = (UniParentalGene) leaves.get(i);
            CompoundSequence h = upgene.getCompoundSequence();
            int numloc = h.getSequenceCount();
            for (int n = 0; n < numloc; n++) {
                Sequence s = h.get(n);
                pw.print(s.getSize());
                pw.print(" ");
            }
            pw.println();
        }
        pw.flush();
        pw.close();
        fout.close();
    } catch (IOException ex) {
        log.error("writeMicsat()", ex);
    }

}