Example usage for java.io PrintWriter printf

List of usage examples for java.io PrintWriter printf

Introduction

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

Prototype

public PrintWriter printf(String format, Object... args) 

Source Link

Document

A convenience method to write a formatted string to this writer using the specified format string and arguments.

Usage

From source file:ngse.org.FileUploadServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Map<String, String> fields = new HashMap<String, String>();
    List<String> fileNames = new ArrayList<String>();

    request.setCharacterEncoding("UTF-8");

    String result = FileUpload(fields, fileNames, request, response);

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=utf-8");
    PrintWriter out = response.getWriter();

    if (result == null || !result.equals("success")) {
        out.printf("{\"status\":100, \"message\":\"%s\"}", result == null ? "" : result);
        return;/*from ww  w. j  a  v a 2 s .  c o  m*/
    }
    String handleClass = fields.get("handleClass");
    if (handleClass == null || handleClass.length() < 1) {
        out.write("{\"status\":100, \"message\":\"unkown handle class\"}");
        return;
    }
    try {
        //handleClass
        Class<?> clazz = Class.forName(handleClass);
        FileUploadServlet servlet = (FileUploadServlet) clazz.newInstance();
        out.write(servlet.run(fields, fileNames));

    } catch (Exception e) {
        e.printStackTrace();
        out.printf("{\"status\":100, \"message\":\"%s\"}", e.getMessage());
        return;
    }
    /*
    if (handleClass != null && handleClass.equals("beans.service.LibraryFileUpload"))
    {
    out.write(new LibraryFileUpload().run(fields, fileNames));
    return;
    }
    if (handleClass != null && handleClass.equals("beans.service.SharedobjectUpload"))
    {
    out.write(new SharedobjectUpload().run(fields, fileNames));
    return;
            
    }
    */

}

From source file:org.ow2.proactive_grid_cloud_portal.cli.EntryPoint.java

private void writeError(ApplicationContext currentContext, String errorMsg, Throwable cause,
        boolean isDebugModeEnabled) {
    PrintWriter writer = new PrintWriter(currentContext.getDevice().getWriter(), true);
    writer.printf("%s", errorMsg);

    if (cause != null) {
        if (cause.getMessage() != null) {
            writer.printf("%n%nError message: %s%n", cause.getMessage());
        }//from w  w  w . j a  v a  2s.c  om

        if (isDebugModeEnabled) {
            if (cause instanceof CLIException && ((CLIException) cause).stackTrace() != null) {
                writer.printf("%nStack trace: %s%n", ((CLIException) cause).stackTrace());
            } else {
                writer.printf("%nStack trace: %s%n", getStackTraceAsString(cause));
            }
        } else {
            writeDebugModeUsageWithBreakEndLine(currentContext);
        }
    }
}

From source file:ch.cyberduck.cli.Console.java

public void printf(final String format, Object... args) {
    if (StringUtils.isEmpty(format)) {
        return;//from w w  w  .j av a 2 s  . c  o m
    }
    try {
        lock.acquire();
        if (console != null) {
            final PrintWriter writer = console.writer();
            if (Arrays.asList(args).isEmpty()) {
                writer.print(format);
            } else {
                writer.printf(format, args);
            }
            writer.flush();
        } else {
            if (Arrays.asList(args).isEmpty()) {
                out.printf(format);
            } else {
                out.printf(format, args);
            }
            out.flush();
        }
    } catch (InterruptedException e) {
        //
    } finally {
        lock.release();
    }
}

From source file:io.github.gsteckman.rpi_rest.SsdpHandler.java

private String generateSearchResponse() throws IOException {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    pw.print("HTTP/1.1 200 OK\r\n");
    pw.printf("CACHE-CONTROL: max-age=%d\r\n", MAX_AGE);
    pw.print("EXT:\r\n");
    pw.printf("LOCATION: http://%s:8080\r\n", getServerAddress());
    pw.print("SERVER: " + System.getProperty("os.name") + "/" + System.getProperty("os.version")
            + ", UPnP/1.1, rpi-rest/0.1\r\n");
    pw.printf("ST: %s\r\n", ST);
    pw.printf("USN: uuid:%s\r\n", getUuid().toString());
    pw.printf("BOOTID.UPNP.ORG: %d\r\n", BOOTID);
    pw.printf("CONFIGID.UPNP.ORG: %d\r\n", CONFIGID);
    pw.printf("\r\n");
    pw.flush();/*w  ww  .  ja va  2  s .  c o  m*/
    String resp = sw.toString();
    pw.close();
    sw.close();
    return resp;
}

From source file:com.wwidesigner.modelling.SupplementaryInfoTable.java

public void printTable(OutputStream os) {
    PrintWriter pw = new PrintWriter(os);
    pw.println(title);/*from   www .  ja va 2s . c om*/
    int col;
    pw.printf("%-11s", getColumnName(0));
    for (col = 1; col < getColumnCount(); col++) {
        if (getColumnName(col).length() < 11) {
            pw.printf("%11s", getColumnName(col));
        } else {
            pw.print("           ");
        }
    }
    pw.println();
    String secondLine = new String();
    for (col = 0; col < getColumnCount(); col++) {
        if (getColumnName(col).length() >= 11) {
            while (secondLine.length() < 11 * col) {
                secondLine += " ";
            }
            secondLine += getColumnName(col);
        }
    }
    if (!secondLine.isEmpty()) {
        pw.println(secondLine);
    }
    for (int row = 0; row < getRowCount(); row++) {
        pw.printf("%-11s", getValueAt(row, 0));
        for (col = 1; col < getColumnCount(); col++) {
            pw.printf("%11s", getValueAt(row, col));
        }
        pw.println();
    }
    pw.println();
    pw.flush();
}

From source file:org.rhq.plugins.platform.content.yum.YumServer.java

/**
 * Setup the /etc/yum.repos.d configuration for this server. The file is over-written to ensure proper content.
 *///  w  w w . ja va 2  s  .c  o  m
private void setupYumConfiguration() {
    File file = new File(yumconf);
    try {
        PrintWriter writer = new PrintWriter(file);
        try {
            writer.println("[rhq]");
            writer.println("name=RHQ");
            writer.printf("baseurl=%s\n", context.baseurl());
            writer.printf("metadata_expire=%d\n", context.getMetadataCacheTimeout());
            writer.println("enabled=1");
            writer.println("gpgcheck=0");
            writer.println("keepalive=0");
            writer.println("timeout=90");
        } finally {
            writer.close();
        }
    } catch (Exception e) {
        String msg = "The yum repo configuration file '" + file + "' could not be created/updated!";
        log.error(msg, e);
    }
}

From source file:com.xtructure.xutil.test.AbstractEntityInfo.java

/** {@inheritDoc} */
@Override//from  w  w  w.j a  va  2s  .  com
public final void write(final File rootDir) throws IOException {
    final PrintWriter out = new PrintWriter( //
            new File(rootDir, getRelativeFileName()));

    out.printf("<html><head><title>TestNG report for %s</title>%n" + "<link rel=\"stylesheet\" " //
            + "href=\"xtructure-testng.css\" type=\"text/css\">%n" //
            + "</head>%n", _name);
    out.printf("<body><h1>TestNG report for %s</h1>%n", _name);
    out.printf("<p>This report was generated on %s.</p>%n", //
            DATE_FORMAT.format(new Date()));
    out.printf("<h2>Summary</h2>%n");
    out.printf("<table class=\"summary\">%n<tbody>%n" + "<tr><th>Failed</th>%s", //
            generateCell("failed", //
                    _stats.getNumFailed(), _stats.getPercentFailed()));
    out.printf("<tr><th>Skipped</th>%s", //
            generateCell("skipped", //
                    _stats.getNumSkipped(), _stats.getPercentSkipped()));
    out.printf("<tr><th>Passed</th>%s</tbody></table>", //
            generateCell("passed", //
                    _stats.getNumPassed(), _stats.getPercentPassed()));

    if (!_children.keySet().isEmpty()) {
        out.printf("<h2>Detailed report</h2>%n");
        out.printf("<table class=\"details\">%n<thead>%n");
        out.printf("%s%n", getDetailTableHeader());
        out.printf("</thead>%n<tbody>%n");
        for (final String childName : new TreeSet<String>(_children.keySet())) {
            out.printf("%s%n", getDetailTableRow(_children.get(childName)));
        }
        out.printf("</tbody>%n</table>%n");
    }
    out.printf("</body>%n</html>%n");

    out.close();

    for (final String childName : _children.keySet()) {
        final C child = _children.get(childName);
        if (child.getRelativeFileName() != null) {
            child.write(rootDir);
        }
    }
}

From source file:org.apache.sling.reqanalyzer.impl.RequestAnalyzerWebConsole.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    PrintWriter pw = resp.getWriter();

    final String fileSize = this.formatByteSize(this.logFile.length());
    pw.printf("<p class='statline ui-state-highlight'>Request Log Size %s</p>%n", fileSize);

    pw.println("<table class='nicetable ui-widget'>");
    pw.println("  <thead>");
    pw.println("    <tr>");
    pw.println("        <th class='ui-widget-header'>Name</th>");
    pw.println("        <th class='ui-widget-header'>Last Update</th>");
    pw.println("        <th class='ui-widget-header'>Size</th>");
    pw.println("        <th class='ui-widget-header'>Action</th>");
    pw.println("    </tr>");
    pw.println("</thead>");
    pw.println("<tbody>");

    pw.println("<tr>");

    pw.printf("<td><a href='${pluginRoot}%s'>%s</a> (<a href='${pluginRoot}%s'>zipped</a>)</td>%n",
            RAW_FILE_MARKER, this.logFile.getName(), ZIP_FILE_MARKER);
    pw.printf("<td>%s</td><td>%s</td>", new Date(this.logFile.lastModified()), fileSize);

    pw.println("<td><ul class='icons ui-widget'>");
    if (canOpenSwingGui(req)) {
        pw.printf(//from w w w.jav  a2 s .  c  om
                "<li title='Analyze Now' class='dynhover ui-state-default ui-corner-all'><a href='${pluginRoot}%s'><span class='ui-icon ui-icon-wrench'></span></a></li>%n",
                WINDOW_MARKER);
        // pw.printf(" (<a href='${pluginRoot}%s'>Analyze Now</a>)", WINDOW_MARKER);
    }
    // pw.println("<li title='Remove File' class='dynhover ui-state-default ui-corner-all'><span class='ui-icon ui-icon-trash'></span></li>");
    pw.println("</ul></td>");

    pw.println("</tr></tbody>");
    pw.println("</table>");

}

From source file:lv.semti.morphology.analyzer.Word.java

public void printShort(PrintWriter stream) {
        if (wordforms.isEmpty()) {
            stream.printf("%s : nav atpazts.\n", token);
        } else {//from  ww  w .j a va 2 s  .c o  m
            for (Wordform variants : wordforms)
                variants.shortDescription(stream);
        }
        stream.flush();
    }

From source file:de.tudarmstadt.ukp.dariah.pipeline.DARIAHWriter.java

private void convert(JCas aJCas, PrintWriter aOut) {
    int paragraphId = 0, sentenceId = 0, tokenId = 0;

    aOut.printf("%s\n", StringUtils.join(getHeader(), "\t"));

    Map<Token, Collection<NamedEntity>> neCoveringMap = JCasUtil.indexCovering(aJCas, Token.class,
            NamedEntity.class);
    Map<Token, Collection<DirectSpeech>> directSpeechCoveringMap = JCasUtil.indexCovering(aJCas, Token.class,
            DirectSpeech.class);

    for (Paragraph para : select(aJCas, Paragraph.class)) {
        for (Sentence sentence : selectCovered(Sentence.class, para)) {
            HashMap<Token, Row> ctokens = new LinkedHashMap<Token, Row>();

            // Tokens
            List<Token> tokens = selectCovered(Token.class, sentence);

            // Check if we should try to include the FEATS in output
            List<Morpheme> morphology = selectCovered(Morpheme.class, sentence);
            boolean useFeats = tokens.size() == morphology.size();

            //Parsing information
            String[] parseFragments = null;
            List<ROOT> root = selectCovered(ROOT.class, sentence);
            if (root.size() == 1) {
                PennTreeNode rootNode = PennTreeUtils.convertPennTree(root.get(0));
                if ("ROOT".equals(rootNode.getLabel())) {
                    rootNode.setLabel("TOP");
                }/*from w ww . j  a v  a 2 s.c  o  m*/
                parseFragments = toPrettyPennTree(rootNode);
            }
            boolean useParseFragements = (parseFragments != null && parseFragments.length == tokens.size());

            for (int i = 0; i < tokens.size(); i++) {
                Row row = new Row();
                row.paragraphId = paragraphId;
                row.sentenceId = sentenceId;
                row.tokenId = tokenId;
                row.token = tokens.get(i);

                if (useParseFragements) {
                    row.parseFragment = parseFragments[i];
                }

                if (useFeats) {
                    row.morphology = morphology.get(i);
                }

                // Named entities
                Collection<NamedEntity> ne = neCoveringMap.get(row.token);
                if (ne.size() > 0)
                    row.ne = ne.toArray(new NamedEntity[0])[0];

                Collection<DirectSpeech> ds = directSpeechCoveringMap.get(row.token);
                if (ds.size() > 0)
                    row.directSpeech = ds.toArray(new DirectSpeech[0])[0];

                ctokens.put(row.token, row);

                tokenId++;
            }

            // Dependencies
            for (Dependency rel : selectCovered(Dependency.class, sentence)) {
                ctokens.get(rel.getDependent()).deprel = rel;
            }

            // Write sentence 
            for (Row row : ctokens.values()) {
                String[] output = getData(ctokens, row);
                aOut.printf("%s\n", StringUtils.join(output, "\t"));
            }

            sentenceId++;
        }
        paragraphId++;
    }
}