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:Executable.LinkImputeR.java

private static void writeSumError(PrintWriter sum, Case c, boolean partial) {
    sum.print(c.getName());
    sum.print("\t");
    sum.print(0);// w ww  .  j  a  va 2s. co m
    sum.print("\t");
    sum.print(0);
    sum.print("\t");
    sum.print(dforms.format(0.0));
    sum.print("\t");
    sum.print(dforms.format(0.0));
    sum.print("\t");
    sum.print(c.getFilterSummary());
    sum.print("\t");
    sum.print(c.getAdditional());

    if (partial) {
        sum.print("\t[");
        sum.print(dforms.format(0.0));
        sum.print("/");
        sum.print(dforms.format(0.0));
        sum.print("]");

        sum.print("\t[");
        sum.print(dforms.format(0.0));
        sum.print("/");
        sum.print(dforms.format(0.0));
        sum.print("]");
    }

    sum.println();
    sum.flush();
}

From source file:eu.brokeratcloud.rest.gui.AdminFacingComponent.java

public static boolean writeFile(String fileName, String content) throws java.io.IOException {
    PrintWriter pw = new PrintWriter(new java.io.FileWriter(fileName, false)); // No append
    try {/*from  ww  w.ja va2s  .c o  m*/
        pw.print(content);
        if (pw.checkError()) {
            logger.error("An error occured while openning or writing output file: " + fileName);
            return false;
        }
    } finally {
        pw.close();
        if (pw.checkError()) {
            logger.error("An error occured while closing output file: " + fileName);
            return false;
        }
    }
    return true;
}

From source file:DateServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession hs = request.getSession(true);

    response.setContentType("text/html");
    PrintWriter pw = response.getWriter();
    pw.print("<B>");

    Date date = (Date) hs.getAttribute("date");
    if (date != null) {
        pw.print("Last access: " + date + "<br>");
    }//from   ww  w .  j  av a2 s .c  o  m

    date = new Date();
    hs.setAttribute("date", date);
    pw.println("Current date: " + date);
}

From source file:de.jgoldhammer.alfresco.jscript.jmx.JmxDumpUtil.java

/**
 * Tabulates a given String -> Object Map.
 * //from w  ww.  j a  va  2 s.  c o m
 * @param keyHeader
 *            the key header
 * @param valueHeader
 *            the value header
 * @param rows
 *            Map containing key value pairs forming the rows
 * @param out
 *            PrintWriter to write the output to
 * @param nestLevel
 *            the nesting level
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static void tabulate(String keyHeader, String valueHeader, Map<String, Object> rows, PrintWriter out,
        int nestLevel) throws IOException {
    if (rows.isEmpty()) {
        return;
    }
    // Calculate column lengths
    int maxKeyLength = keyHeader.length(), maxValLength = valueHeader.length();
    for (Map.Entry<String, Object> entry : rows.entrySet()) {
        maxKeyLength = Math.max(maxKeyLength, entry.getKey().length());
        maxValLength = Math.max(maxValLength, getValueLength(entry.getValue()));
    }
    // Output Header
    outputRow(out, maxKeyLength, keyHeader, valueHeader, nestLevel);
    indent(out, nestLevel);
    for (int col = 0; col < maxKeyLength; col++) {
        out.print('-');
    }
    out.print(' ');
    for (int col = 0; col < maxValLength; col++) {
        out.print('-');
    }
    out.println();

    // Output Body
    for (Map.Entry<String, Object> entry : rows.entrySet()) {
        outputRow(out, maxKeyLength, entry.getKey(), entry.getValue(), nestLevel);
    }
    out.println();
}

From source file:com.uniquesoft.uidl.servlet.UploadServlet.java

/**
 * Writes a response to the client.//from ww w .j  a va2 s  .com
 */
protected static void renderMessage(HttpServletResponse response, String message, String contentType)
        throws IOException {
    response.addHeader("Cache-Control", "no-cache");
    response.setContentType(contentType + "; charset=GB2312");
    response.setCharacterEncoding("GB2312");
    PrintWriter out = response.getWriter();
    out.print(message);

    System.out.println("=======>" + message);
    out.flush();
    out.close();
}

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

public void render(PrintWriter printWriter) throws IOException {
    printWriter.print(text);
}

From source file:com.google.android.gcm.demo.server.AlertsServlet.java

/**
 * Displays the existing messages and offer the option to send a new one.
 *///from   w w w .j av  a 2 s .  com
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("application/json");

    String limit = req.getParameter("limit");
    String offset = req.getParameter("offset");

    JSONArray alerts = Datastore.getAllAlerts(Integer.parseInt(offset), Integer.parseInt(limit));
    PrintWriter out = resp.getWriter();
    out.print(alerts);
    resp.setStatus(HttpServletResponse.SC_OK);
}

From source file:LVCoref.MMAX2.java

public static void exportNeAnnotation(Document d, String export_filename) {
    PrintWriter out;
    try {// www .ja v  a 2s .c  o m
        String eol = System.getProperty("line.separator");
        out = new PrintWriter(new FileWriter(export_filename));
        StringBuilder s = new StringBuilder();
        for (Node n : d.tree) {
            s.append(n.conll_fields.get(1));
            s.append("\t");
            s.append(n.conll_fields.get(3).charAt(0));
            s.append("\t");
            s.append(n.conll_fields.get(2));
            s.append("\t");
            s.append(n.conll_fields.get(4));
            s.append("\t");
            if (n.ne_annotation.length() == 0)
                n.ne_annotation = "O";
            s.append(n.ne_annotation);
            s.append(eol);
            if (n.sentEnd)
                s.append(eol);
        }
        out.print(s.toString());
        out.flush();
        out.close();
    } catch (IOException ex) {
        Logger.getLogger(Document.class.getName()).log(Level.SEVERE, null, ex);
        System.err.println("ERROR: couldn't create/open output conll file");
    }
}

From source file:main.java.vasolsim.common.file.ExamBuilder.java

/**
 * writes an editable, unlocked exam to a file
 *
 * @param exam      the exam to be written
 * @param examFile  the target file/*from w  w  w  . j av  a  2  s.c o  m*/
 * @param overwrite if an existing file can be overwritten
 *
 * @return if the file write was successful
 *
 * @throws VaSolSimException
 */
public static boolean writeRaw(@Nonnull Exam exam, @Nonnull File examFile, boolean overwrite)
        throws VaSolSimException {
    /*
     * check the file creation status and handle it
     */
    //if it exists
    if (examFile.isFile()) {
        //can't overwrite
        if (!overwrite) {
            throw new VaSolSimException(ERROR_MESSAGE_FILE_ALREADY_EXISTS);
        }
        //can overwrite, clear the existing file
        else {
            PrintWriter printWriter;
            try {
                printWriter = new PrintWriter(examFile);
            } catch (FileNotFoundException e) {
                throw new VaSolSimException(ERROR_MESSAGE_FILE_NOT_FOUND_AFTER_INTERNAL_CHECK);
            }

            printWriter.print("");
            printWriter.close();
        }
    }
    //no file, create one
    else {
        if (!examFile.getParentFile().isDirectory() && !examFile.getParentFile().mkdirs()) {
            throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_DIRS);
        }

        try {
            if (!examFile.createNewFile()) {
                throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_FILE);
            }
        } catch (IOException e) {
            throw new VaSolSimException(ERROR_MESSAGE_CREATE_FILE_EXCEPTION);
        }
    }

    /*
     * initialize the document
     */
    Document examDoc;
    Transformer examTransformer;
    try {
        examDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

        examTransformer = TransformerFactory.newInstance().newTransformer();
        examTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
        examTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
        examTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        examTransformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd");
        examTransformer.setOutputProperty(INDENTATION_KEY, "4");
    } catch (ParserConfigurationException e) {
        throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_XML_PARSER_INITIALIZATION_EXCEPTION, e);
    } catch (TransformerConfigurationException e) {
        throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_TRANSFORMER_CONFIGURATION, e);
    }

    /*
     * build exam info
     */
    Element root = examDoc.createElement(XML_ROOT_ELEMENT_NAME);
    examDoc.appendChild(root);

    Element info = examDoc.createElement(XML_INFO_ELEMENT_NAME);
    root.appendChild(info);

    //exam info
    GenericUtils.appendSubNode(XML_TEST_NAME_ELEMENT_NAME, exam.getTestName(), info, examDoc);
    GenericUtils.appendSubNode(XML_AUTHOR_NAME_ELEMENT_NAME, exam.getAuthorName(), info, examDoc);
    GenericUtils.appendSubNode(XML_SCHOOL_NAME_ELEMENT_NAME, exam.getSchoolName(), info, examDoc);
    GenericUtils.appendSubNode(XML_PERIOD_NAME_ELEMENT_NAME, exam.getPeriodName(), info, examDoc);

    //start security xml section
    Element security = examDoc.createElement(XML_SECURITY_ELEMENT_NAME);
    root.appendChild(security);

    GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_ELEMENT_NAME,
            Boolean.toString(exam.isReportingStats()), security, examDoc);
    GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_STANDALONE_ELEMENT_NAME,
            Boolean.toString(exam.isReportingStatsStandalone()), security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_DESTINATION_EMAIL_ADDRESS_ELEMENT_NAME,
            exam.getStatsDestinationEmail(), security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_EMAIL_ADDRESS_ELEMENT_NAME, exam.getStatsSenderEmail(),
            security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_ADDRESS_ELEMENT_NAME,
            exam.getStatsSenderSMTPAddress(), security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_PORT_ELEMENT_NAME,
            Integer.toString(exam.getStatsSenderSMTPPort()), security, examDoc);

    ArrayList<QuestionSet> questionSets = exam.getQuestionSets();
    if (GenericUtils.verifyQuestionSetsIntegrity(questionSets)) {
        for (int setsIndex = 0; setsIndex < questionSets.size(); setsIndex++) {
            QuestionSet qSet = questionSets.get(setsIndex);

            Element qSetElement = examDoc.createElement(XML_QUESTION_SET_ELEMENT_NAME);
            root.appendChild(qSetElement);

            GenericUtils.appendSubNode(XML_QUESTION_SET_ID_ELEMENT_NAME, Integer.toString(setsIndex + 1),
                    qSetElement, examDoc);
            GenericUtils.appendSubNode(XML_QUESTION_SET_NAME_ELEMENT_NAME,
                    (qSet.getName() == null || qSet.getName().equals("")) ? "Question Set " + (setsIndex + 1)
                            : qSet.getName(),
                    qSetElement, examDoc);
            GenericUtils.appendSubNode(XML_QUESTION_SET_RESOURCE_TYPE_ELEMENT_NAME,
                    qSet.getResourceType().toString(), qSetElement, examDoc);

            if (qSet.getResources() != null) {
                for (BufferedImage img : qSet.getResources()) {
                    try {
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        ImageIO.write(img, "png", out);
                        out.flush();
                        GenericUtils.appendSubNode(XML_QUESTION_SET_RESOURCE_DATA_ELEMENT_NAME,
                                convertBytesToHexString(out.toByteArray()), qSetElement, examDoc);
                    } catch (IOException e) {
                        throw new VaSolSimException("Error: cannot write images to byte array for transport");
                    }
                }
            }

            for (int setIndex = 0; setIndex < qSet.getQuestions().size(); setIndex++) {
                Question question = qSet.getQuestions().get(setIndex);

                Element qElement = examDoc.createElement(XML_QUESTION_ELEMENT_NAME);
                qSetElement.appendChild(qElement);

                GenericUtils.appendSubNode(XML_QUESTION_ID_ELEMENT_NAME, Integer.toString(setIndex + 1),
                        qElement, examDoc);
                GenericUtils.appendSubNode(XML_QUESTION_NAME_ELEMENT_NAME,
                        (question.getName() == null || question.getName().equals(""))
                                ? "Question " + (setIndex + 1)
                                : question.getName(),
                        qElement, examDoc);
                GenericUtils.appendSubNode(XML_QUESTION_TEXT_ELEMENT_NAME, question.getQuestion(), qElement,
                        examDoc);
                GenericUtils.appendSubNode(XML_QUESTION_SCRAMBLE_ANSWERS_ELEMENT_NAME,
                        Boolean.toString(question.getScrambleAnswers()), qElement, examDoc);
                GenericUtils.appendSubNode(XML_QUESTION_REATIAN_ANSWER_ORDER_ELEMENT_NAME,
                        Boolean.toString(question.getAnswerOrderMatters()), qElement, examDoc);

                for (AnswerChoice answer : question.getCorrectAnswerChoices()) {
                    GenericUtils.appendSubNode(XML_QUESTION_ENCRYPTED_ANSWER_HASH, answer.getAnswerText(),
                            qElement, examDoc);
                }

                for (int questionIndex = 0; questionIndex < question.getAnswerChoices()
                        .size(); questionIndex++) {
                    AnswerChoice ac = question.getAnswerChoices().get(questionIndex);

                    Element acElement = examDoc.createElement(XML_ANSWER_CHOICE_ELEMENT_NAME);
                    qElement.appendChild(acElement);

                    GenericUtils.appendSubNode(XML_ANSWER_CHOICE_ID_ELEMENT_NAME,
                            Integer.toString(questionIndex + 1), acElement, examDoc);
                    GenericUtils.appendSubNode(XML_ANSWER_CHOICE_VISIBLE_ID_ELEMENT_NAME,
                            ac.getVisibleChoiceID(), acElement, examDoc);
                    GenericUtils.appendSubNode(XML_ANSWER_TEXT_ELEMENT_NAME, ac.getAnswerText(), acElement,
                            examDoc);
                }
            }
        }
    }

    return true;
}

From source file:net.chwise.websearch.Mol2SmilesServlet.java

@Override
public void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String mol = req.getParameter("mol");
    ToSmilesConverter converter = new ToSmilesConverter();
    String smiles = converter.convert(mol);
    JSONObject jsonDoc = new JSONObject();

    LOGGER.log(Level.INFO, "Molfile to convert: {0}", mol);

    try {//from w  ww . j  a  v a2  s.  com
        jsonDoc.put("smiles", smiles);
    } catch (JSONException e) {
        throw new RuntimeException("Exception in Mol2SmilesServlet", e);
    }

    resp.setContentType("application/json");
    PrintWriter out = resp.getWriter();
    out.print(jsonDoc);
    out.flush();
}