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:dictinsight.utils.io.HttpUtils.java

public static String getDataFromOtherServer(String url, String param) {
    PrintWriter out = null;
    BufferedReader in = null;//from  w  w  w  . jav  a2  s .  c o m
    String result = "";
    try {
        URL realUrl = new URL(url);
        URLConnection conn = realUrl.openConnection();
        conn.setConnectTimeout(1000 * 10);
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        out = new PrintWriter(conn.getOutputStream());
        out.print(param);
        out.flush();
        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        System.out.println("get date from " + url + param + " error!");
        e.printStackTrace();
    }
    // finally?????
    finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return result;
}

From source file:cn.jpush.hdfs.mr.example.BaileyBorweinPlouffe.java

/** Print out elements in a nice format. */
private static <T> void print(PrintWriter out, Iterator<T> iterator, String prefix, String format,
        int elementsPerGroup, int groupsPerLine) {
    final StringBuilder sb = new StringBuilder("\n");
    for (int i = 0; i < prefix.length(); i++)
        sb.append(" ");
    final String spaces = sb.toString();

    out.print("\n" + prefix);
    for (int i = 0; iterator.hasNext(); i++) {
        if (i > 0 && i % elementsPerGroup == 0)
            out.print((i / elementsPerGroup) % groupsPerLine == 0 ? spaces : " ");
        out.print(String.format(format, iterator.next()));
    }/* ww w.ja  v a  2s  .c o m*/
    out.println();
}

From source file:de.escidoc.core.aa.servlet.Login.java

/**
 * Initializes the redirect to the provided URL and writes the provided page content to the writer of the {@link
 * HttpServletResponse}. The http status code is set to SEE_OTHER.
 *
 * @param response    The {@link HttpServletResponse}.
 * @param page        The page to write.
 * @param redirectUrl The URL to that the user shall be redirected.
 * @throws IOException Thrown in case of a failed i/o operation.
 *//*from w  w w .j a v  a2s. com*/
private static void sendRedirectingResponse(final HttpServletResponse response, final String page,
        final String redirectUrl) throws IOException {

    final PrintWriter writer = response.getWriter();
    writer.print(page);
    // TODO: which response/status code? sendRedirect uses 302. 307 must
    // not be used since this results in forwarding the post of login data.
    // Maybe, 303 should be used to force the browser to redirect with GET,
    // as redirect with POST is prohibited?
    // Or should a form be returned and the user posts the handle back to
    // the application (similar to Shibboleth's Browser/Post profile)?
    response.setStatus(HttpServletResponse.SC_SEE_OTHER);
    response.setHeader("Location", redirectUrl);
    //        response.flushBuffer();
}

From source file:net.metanotion.sqlc.SQLC.java

private static void generateStructs(final String outputFolder, final StructManager sm,
        final Set<String> implicits, final Map<String, String> implicitDocs,
        final Map<String, Boolean> implicitVisibility, final Iterable<String> srcPathes) throws IOException {
    for (final Map.Entry<String, GetInitializer> e : sm) {
        if (!implicits.contains(e.getKey())) {
            continue;
        }//from  w  w w .j  av  a 2 s  .  com
        final String visibility = implicitVisibility.get(e.getKey()).booleanValue() ? "public " : " ";
        final String docString = implicitDocs.get(e.getKey());
        final GetInitializer gi = e.getValue();
        if (needToGenerateStruct(e.getKey(), gi, srcPathes)) {
            final Struct s = (Struct) gi;
            final String[] name = e.getKey().split("\\.");
            final String[] pkg = new String[name.length - 1];
            for (int i = 0; i < pkg.length; i++) {
                pkg[i] = name[i];
            }
            final FileOutputStream fos = new FileOutputStream(mkPath(outputFolder, pkg, name[pkg.length]));
            final PrintWriter writer = new PrintWriter(new OutputStreamWriter(fos, "UTF-8"));
            if (pkg.length > 0) {
                writer.print("package ");
                String sep = "";
                for (String pe : pkg) {
                    writer.print(sep + pe);
                    sep = ".";
                }
                writer.println(";");
                writer.println("");
            }

            System.out.println("GENERATING: " + visibility + " " + name[pkg.length]);
            writer.print("/** ");
            if (docString != null) {
                writer.println(docString.substring(3, docString.length() - 2));
            }
            writer.println("<i>This is a data/struct/value class generated by the SQLC compiler.</i> */");
            writer.println("@javax.annotation.Generated(\"net.metanotion.sqlc.SQLC\") " + visibility
                    + "final class " + name[pkg.length] + " {");
            for (final String p : s.listProperties()) {
                writer.print("\tpublic ");
                writer.print(s.getType(p));
                writer.println(" " + p + ";");
            }
            writer.println("}");
            writer.close();
            fos.close();
        }
    }
}

From source file:gov.nih.nci.caarray.application.translation.geosoft.GeoSoftFileWriterUtil.java

private static void writeOrganism(Set<Source> sources, Set<Sample> samples, Experiment exp, PrintWriter out) {
    final Set<Organism> all = new TreeSet<Organism>(ENTITY_COMPARATOR);
    for (final Source source : sources) {
        addIgnoreNull(all, source.getOrganism());
    }/*from  w  w w.j av  a 2s.c  om*/
    for (final Sample sample : samples) {
        addIgnoreNull(all, sample.getOrganism());
    }
    if (all.isEmpty()) {
        all.add(exp.getOrganism());
    }
    for (final Organism o : all) {
        out.print("!Sample_organism=");
        out.println(o.getScientificName());
    }
}

From source file:com.emc.ecs.sync.cli.CliHelper.java

public static String longHelp() {
    StringWriter helpWriter = new StringWriter();
    PrintWriter pw = new PrintWriter(helpWriter);
    HelpFormatter fmt = new HelpFormatter();
    fmt.setWidth(79);//from  w  w  w . j ava 2  s.  c  o m

    // main CLI options
    Options options = ConfigUtil.wrapperFor(CliConfig.class).getOptions();

    // sync options
    for (Option o : ConfigUtil.wrapperFor(SyncOptions.class).getOptions().getOptions()) {
        options.addOption(o);
    }

    // Make sure we do CommonOptions first
    String usage = "java -jar ecs-sync.jar -source <source-uri> [-filters <filter1>[,<filter2>,...]] -target <target-uri> [options]";
    fmt.printHelp(pw, fmt.getWidth(), usage, "Common options:", options, fmt.getLeftPadding(),
            fmt.getDescPadding(), null);

    pw.print("\nAvailable plugins are listed below along with any custom options they may have\n");

    // Do the rest
    for (ConfigWrapper<?> storageWrapper : ConfigUtil.allStorageConfigWrappers()) {
        pw.write('\n');
        pw.write(String.format("%s (%s)\n", storageWrapper.getLabel(), storageWrapper.getUriPrefix()));
        fmt.printWrapped(pw, fmt.getWidth(), 4, "    " + storageWrapper.getDocumentation());
        fmt.printWrapped(pw, fmt.getWidth(), 4,
                "    NOTE: Storage options must be prefixed by source- or target-, depending on which role they assume");
        fmt.printOptions(pw, fmt.getWidth(), storageWrapper.getOptions(), fmt.getLeftPadding(),
                fmt.getDescPadding());
    }
    for (ConfigWrapper<?> filterWrapper : ConfigUtil.allFilterConfigWrappers()) {
        pw.write('\n');
        pw.write(String.format("%s (%s)\n", filterWrapper.getLabel(), filterWrapper.getCliName()));
        fmt.printWrapped(pw, fmt.getWidth(), 4, "    " + filterWrapper.getDocumentation());
        fmt.printOptions(pw, fmt.getWidth(), filterWrapper.getOptions(), fmt.getLeftPadding(),
                fmt.getDescPadding());
    }

    return helpWriter.toString();
}

From source file:com.dien.upload.server.UploadServlet.java

/**
 * Writes a response to the client./*from  w ww  .j  av a 2s .  co  m*/
 */
protected static void renderMessage(HttpServletResponse response, String message, String contentType)
        throws IOException {
    response.setContentType(contentType + "; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();
    out.print(message);
    out.flush();
    out.close();
}

From source file:net.metanotion.sqlc.SQLC.java

private static void generateExceptions(final String outputFolder, final Map<String, ExceptionInfo> exceptions,
        final Map<String, String> inheritanceMap, final Set<String> implicits,
        final Map<String, String> implicitDocs, final Map<String, Boolean> implicitVisibility)
        throws IOException {
    for (final Map.Entry<String, ExceptionInfo> ex : exceptions.entrySet()) {
        if (!implicits.contains(ex.getKey())) {
            continue;
        }//from   w  w  w . j  a v a  2  s. com
        final String visibility = implicitVisibility.get(ex.getKey()).booleanValue() ? "public " : " ";
        final String docString = implicitDocs.get(ex.getKey());
        final String[] name = ex.getKey().split("\\.");
        final String[] pkg = new String[name.length - 1];
        for (int i = 0; i < pkg.length; i++) {
            pkg[i] = name[i];
        }
        final FileOutputStream fos = new FileOutputStream(mkPath(outputFolder, pkg, name[pkg.length]));
        final PrintWriter writer = new PrintWriter(new OutputStreamWriter(fos, "UTF-8"));
        if (pkg.length > 0) {
            writer.print("package ");
            String sep = "";
            for (String pe : pkg) {
                writer.print(sep + pe);
                sep = ".";
            }
            writer.println(";");
            writer.println("");
        }
        writer.print("/** ");
        if (docString != null) {
            writer.println(docString.substring(3, docString.length() - 2));
        }
        writer.println("<i>This is an exception class generated by the SQLC compiler.</i> */");
        writer.println("@javax.annotation.Generated(\"net.metanotion.sqlc.SQLC\") " + visibility + "class "
                + name[pkg.length] + " extends ");
        final String parent = inheritanceMap.get(ex.getKey());
        writer.println((parent == null) ? "java.lang.Exception" : parent);
        writer.println(" {");
        int curriedParamCount = 0;
        for (final Pair<String, Object> param : ex.getValue().params) {
            writer.println("\tpublic final " + valueType(param.getValue()) + " " + param.getKey() + ";");
            if (param.getValue() != null) {
                curriedParamCount++;
            }
        }
        while (curriedParamCount > 0) {
            writer.println("\t" + name[pkg.length] + "(");
            String sep = "\t\t";
            int curryCount = curriedParamCount;
            for (final Pair<String, Object> param : ex.getValue().params) {
                if ((param.getValue() != null) && (curryCount > 0)) {
                    curryCount--;
                    continue;
                }
                writer.println(sep + "final " + valueType(param.getValue()) + " " + param.getKey());
                sep = "\t\t, ";
            }
            writer.println("\t) { this(");
            curryCount = curriedParamCount;
            sep = "\t\t";
            for (final Pair<String, Object> param : ex.getValue().params) {
                if ((param.getValue() != null) && (curryCount > 0)) {
                    writer.println(sep + param.getValue().toString());
                    curryCount--;
                } else {
                    writer.println(sep + param.getKey());
                }
                sep = "\t\t, ";
            }
            writer.println("\t); }");
            curriedParamCount--;
        }
        writer.println("\t" + name[pkg.length] + "(");
        String sep = "\t\t";
        for (final Pair<String, Object> param : ex.getValue().params) {
            writer.println(sep + "final " + valueType(param.getValue()) + " " + param.getKey());
            sep = "\t\t, ";
        }
        writer.println("\t) {");
        writer.println("\t\tsuper();");
        for (final Pair<String, Object> param : ex.getValue().params) {
            writer.println("\t\tthis." + param.getKey() + " = " + param.getKey() + ";");
        }
        writer.println("\t}");
        for (final Pair<String, Object> param : ex.getValue().params) {
            final String key = param.getKey();
            writer.println("\tpublic " + valueType(param.getValue()) + " get"
                    + key.substring(0, 1).toUpperCase() + key.substring(1) + "() {");
            writer.println("\t\treturn this." + key + ";");
            writer.println("\t}");
        }
        writer.println("}");
        writer.close();
        fos.close();
    }
}

From source file:com.headswilllol.basiclauncher.Launcher.java

public static void createExceptionLog(Exception ex, boolean gameThread) {
    Calendar cal = Calendar.getInstance();
    String minute = cal.get(Calendar.MINUTE) + "";
    minute = (minute.length() < 2 ? "0" : "") + minute;
    String second = cal.get(Calendar.SECOND) + "";
    second = (second.length() < 2 ? "0" : "") + second;
    String time = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-"
            + cal.get(Calendar.DAY_OF_MONTH) + "_" + cal.get(Calendar.HOUR_OF_DAY) + "-" + minute + "-" + second
            + "-" + cal.get(Calendar.MILLISECOND);
    try {/*from ww  w . j  a va 2  s  .c  o  m*/
        if (!new File(appData(), FOLDER_NAME + File.separator + "errorlogs").exists())
            new File(appData(), FOLDER_NAME + File.separator + "errorlogs").mkdir();
        new File(appData(), FOLDER_NAME + File.separator + "errorlogs" + File.separator + time + ".log")
                .createNewFile();
        System.out.println("Saved error log to " + appData() + File.separator + FOLDER_NAME + File.separator
                + "errorlogs" + File.separator + time + ".log");
        PrintWriter writer = new PrintWriter(appData() + File.separator + FOLDER_NAME + File.separator
                + "errorlogs" + File.separator + time + ".log", "UTF-8");
        writer.print(getLogHeader(gameThread));
        ex.printStackTrace(writer);
        writer.print("-----------------END ERROR LOG-----------------\n");
        writer.close();
    } catch (Exception exc) {
        // Well, shit.
        exc.printStackTrace();
        Launcher.progress = "An exception occurred while saving an exception log.";
        Launcher.fail = "Errors occurred; see console for details.";
    }
}

From source file:com.headswilllol.basiclauncher.Launcher.java

public static void createExceptionLog(String s, boolean gameThread) {
    String log = getLogHeader(gameThread);
    log += s;//w w w. j  a  v  a  2  s .  c o m
    log += "\n-----------------END ERROR LOG-----------------\n";
    Calendar cal = Calendar.getInstance();
    String minute = cal.get(Calendar.MINUTE) + "";
    if (minute.length() < 2)
        minute = "0" + minute;
    String second = cal.get(Calendar.SECOND) + "";
    if (second.length() < 2)
        second = "0" + second;
    String time = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-"
            + cal.get(Calendar.DAY_OF_MONTH) + "_" + cal.get(Calendar.HOUR_OF_DAY) + "-" + minute + "-" + second
            + "-" + cal.get(Calendar.MILLISECOND);
    try {
        if (!new File(appData(), FOLDER_NAME + File.separator + "errorlogs").exists())
            new File(appData(), FOLDER_NAME + File.separator + "errorlogs").mkdir();
        new File(appData(), FOLDER_NAME + File.separator + "errorlogs" + File.separator + time + ".log")
                .createNewFile();
        System.out.println("Saved error log to " + appData() + File.separator + FOLDER_NAME + File.separator
                + "errorlogs" + File.separator + time + ".log");
        PrintWriter writer = new PrintWriter(appData() + File.separator + FOLDER_NAME + File.separator
                + "errorlogs" + File.separator + time + ".log", "UTF-8");
        writer.print(log);
        writer.close();
    } catch (Exception ex) {
        // Well, shit.
        ex.printStackTrace();
        Launcher.progress = "An exception occurred while saving an exception log.";
        Launcher.fail = "Errors occurred; see console for details.";
    }
}