Example usage for java.io Writer write

List of usage examples for java.io Writer write

Introduction

In this page you can find the example usage for java.io Writer write.

Prototype

public void write(String str) throws IOException 

Source Link

Document

Writes a string.

Usage

From source file:com.day.cq.wcm.foundation.forms.LayoutHelper.java

/**
 * Print all errors (if there are any.) If there are error messages for this
 * field, a div for each error message is created. The div has the class
 * form_row, then {@link #printTitle(String, String, boolean, Writer)} is
 * called and a third inner div with the message and the classes
 * form_rightcol and form_error is created.
 *
 * @param request   The current request.
 * @param fieldName The name of the field (not the id!)
 * @param hideLabel Option to completely hide the label (removes form_leftcollabel and form_leftcolmark
 * divs content)/*from  w  w w  . ja va 2  s. c  o m*/
 * @param out       The writer.
 * @throws IOException If writing fails.
 * @since 5.4
 */
public static void printErrors(SlingHttpServletRequest request, String fieldName, boolean hideLabel, Writer out)
        throws IOException {
    final ValidationInfo info = ValidationInfo.getValidationInfo(request);
    // check if we have validation errors
    if (info != null) {
        String[] msgs = info.getErrorMessages(fieldName);
        if (msgs != null) {
            for (String msg : msgs) {
                out.write("<div class=\"form_row\">");
                printTitle(null, null, false, hideLabel, out);
                out.write("<div class=\"form_rightcol form_error\">");
                String[] msgParas = msg.split("\n");
                for (int i = 0; i < msgParas.length; i++) {
                    out.write(StringEscapeUtils.escapeHtml4(msgParas[i]));
                    if (i + 1 < msgParas.length) {
                        out.write("<br>");
                    }
                }
                out.write("</div>");
                out.write("</div>");
            }
        }
    }
}

From source file:dataGen.DataGen.java

/**
 * Saves the Data/*from  w  w  w.  ja va  2  s. c om*/
 * @param values
 *       The values which should be saved.
 * @param fw
 *       The File-Writer including the File location
 * @param nf
 *       How should the data get formatted?
 * @throws IOException
 *       If Stream to a File couldn't be written/closed 
 */
public static void saveData(Array2DRowRealMatrix values, Writer fw, NumberFormat nf) throws IOException {
    for (int i = 0; i < values.getRowDimension(); i++) {
        String row = i + 1 + " ";
        //String row = "";

        for (int j = 0; j < values.getColumnDimension(); j++) {
            row = row + nf.format(values.getEntry(i, j)) + " ";
        }
        fw.write(row);
        fw.append(System.getProperty("line.separator"));
    }
    fw.close();
}

From source file:net.sf.jasperreports.engine.export.JsonExporter.java

public static void writeParts(JasperPrint jasperPrint, Writer writer) throws IOException {
    PrintParts parts = jasperPrint.getParts();
    writer.write("{");

    writer.write("\"id\": \"parts_" + (parts.hashCode() & 0x7FFFFFFF) + "\",");
    writer.write("\"type\": \"reportparts\",");
    writer.write("\"parts\": [");

    if (!parts.startsAtZero()) {
        writer.write("{\"idx\": 0, \"name\": \"");
        writer.write(JsonStringEncoder.getInstance().quoteAsString(jasperPrint.getName()));
        writer.write("\"}");
        if (parts.partCount() > 1) {
            writer.write(",");
        }//  w w w .j  a  v  a 2 s  .co m
    }

    Iterator<Map.Entry<Integer, PrintPart>> it = parts.partsIterator();

    while (it.hasNext()) {
        Map.Entry<Integer, PrintPart> partsEntry = it.next();
        int idx = partsEntry.getKey();
        PrintPart part = partsEntry.getValue();

        writer.write("{\"idx\": " + idx + ", \"name\": \"");
        writer.write(JsonStringEncoder.getInstance().quoteAsString(part.getName()));
        writer.write("\"}");
        if (it.hasNext()) {
            writer.write(",");
        }
    }

    writer.write("]");
    writer.write("}");
}

From source file:Main.java

/**
 * Pulled from apache lang commons project (StringUtils).
 * /*from   w w  w .  j  a  va  2s  .c  om*/
 * <p>Worker method for the {@link #escapeJavaScript(String)} method.</p>
 * 
 * @param out write to receieve the escaped string
 * @param str String to escape values in, may be null
 * @param escapeSingleQuote escapes single quotes if <code>true</code>. For Java this is usually false and for Javascript it is true.
 * @throws IOException if an IOException occurs
 */
private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote)
        throws IOException {
    if (out == null) {
        throw new IllegalArgumentException("The Writer must not be null");
    }
    if (str == null) {
        return;
    }
    int sz;
    sz = str.length();
    for (int i = 0; i < sz; i++) {
        char ch = str.charAt(i);

        // handle unicode
        if (ch > 0xfff) {
            out.write("\\u" + hex(ch));
        } else if (ch > 0xff) {
            out.write("\\u0" + hex(ch));
        } else if (ch > 0x7f) {
            out.write("\\u00" + hex(ch));
        } else if (ch < 32) {
            switch (ch) {
            case '\b':
                out.write('\\');
                out.write('b');
                break;
            case '\n':
                out.write('\\');
                out.write('n');
                break;
            case '\t':
                out.write('\\');
                out.write('t');
                break;
            case '\f':
                out.write('\\');
                out.write('f');
                break;
            case '\r':
                out.write('\\');
                out.write('r');
                break;
            default:
                if (ch > 0xf) {
                    out.write("\\u00" + hex(ch));
                } else {
                    out.write("\\u000" + hex(ch));
                }
                break;
            }
        } else {
            switch (ch) {
            case '\'':
                if (escapeSingleQuote) {
                    out.write('\\');
                }
                out.write('\'');
                break;
            case '"':
                out.write('\\');
                out.write('"');
                break;
            case '\\':
                out.write('\\');
                out.write('\\');
                break;
            case '/':
                out.write('\\');
                out.write('/');
                break;
            default:
                out.write(ch);
                break;
            }
        }
    }
}

From source file:com.day.cq.wcm.foundation.forms.LayoutHelper.java

/**
 * Print all errors (if there are any.) If there are error messages for this
 * field, a div for each error message is created. The div has the class
 * form_row, then {@link #printTitle(String, String, boolean, Writer)} is
 * called and a third inner div with the message and the classes
 * form_rightcol and form_error is created.
 *
 * @param request   The current request.
 * @param fieldName The name of the field (not the id!)
 * @param hideLabel Option to completely hide the label (removes form_leftcollabel and form_leftcolmark
 * divs content)//from  w  w w .jav  a2s .c o m
 * @param out       The writer.
 * @return Returns <code>true</code> if an error has been printed (since 5.5)
 * @throws IOException If writing fails.
 * @since 5.4
 */
public static boolean printErrors(SlingHttpServletRequest request, String fieldName, boolean hideLabel,
        Writer out, final int valueIndex) throws IOException {
    final ValidationInfo info = ValidationInfo.getValidationInfo(request);
    // check if we have validation errors
    if (info != null) {
        String[] msgs = info.getErrorMessages(fieldName, valueIndex);
        if (msgs != null) {
            for (String msg : msgs) {
                out.write("<div class=\"form_row\">");
                printTitle(null, null, false, hideLabel, out);
                out.write("<div class=\"form_rightcol form_error\">");
                String[] msgParas = msg.split("\n");
                for (int i = 0; i < msgParas.length; i++) {
                    out.write(StringEscapeUtils.escapeHtml4(msgParas[i]));
                    if (i + 1 < msgParas.length) {
                        out.write("<br>");
                    }
                }
                out.write("</div>");
                out.write("</div>");
            }
            return true;
        }
    }
    return false;
}

From source file:ca.rmen.android.networkmonitor.app.email.Emailer.java

/**
 * Sends an e-mail in UTF-8 encoding./*from   w  w w. jav a2s  .  c  o  m*/
 *
 * @param protocol    this has been tested with "TLS", "SSL", and null.
 * @param attachments optional attachments to include in the mail.
 * @param debug       if true, details about the smtp commands will be logged to stdout.
 */
static void sendEmail(String protocol, String server, int port, String user, String password, String from,
        String[] recipients, String subject, String body, Set<File> attachments, boolean debug)
        throws Exception {

    // Set up the mail connectivity
    final AuthenticatingSMTPClient client;
    if (protocol == null)
        client = new AuthenticatingSMTPClient();
    else
        client = new AuthenticatingSMTPClient(protocol);

    if (debug)
        client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    client.setDefaultTimeout(SMTP_TIMEOUT_MS);
    client.setCharset(Charset.forName(ENCODING));
    client.connect(server, port);
    checkReply(client);
    client.helo("[" + client.getLocalAddress().getHostAddress() + "]");
    checkReply(client);
    if ("TLS".equals(protocol)) {
        if (!client.execTLS()) {
            checkReply(client);
            throw new RuntimeException("Could not start tls");
        }
    }
    client.auth(AuthenticatingSMTPClient.AUTH_METHOD.LOGIN, user, password);
    checkReply(client);

    // Set up the mail participants
    client.setSender(from);
    checkReply(client);
    for (String recipient : recipients) {
        client.addRecipient(recipient);
        checkReply(client);
    }

    // Set up the mail content
    Writer writer = client.sendMessageData();
    SimpleSMTPHeader header = new SimpleSMTPHeader(from, recipients[0], subject);
    for (int i = 1; i < recipients.length; i++)
        header.addCC(recipients[i]);

    // Just plain text mail: no attachments
    if (attachments == null || attachments.isEmpty()) {
        header.addHeaderField("Content-Type", "text/plain; charset=" + ENCODING);
        writer.write(header.toString());
        writer.write(body);
    }
    // Mail with attachments
    else {
        String boundary = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 28);
        header.addHeaderField("Content-Type", "multipart/mixed; boundary=" + boundary);
        writer.write(header.toString());

        // Write the main text message
        writer.write("--" + boundary + "\n");
        writer.write("Content-Type: text/plain; charset=" + ENCODING + "\n\n");
        writer.write(body);
        writer.write("\n");

        // Write the attachments
        appendAttachments(writer, boundary, attachments);
        writer.write("--" + boundary + "--\n\n");
    }

    writer.close();
    if (!client.completePendingCommand()) {
        throw new RuntimeException("Could not send mail");
    }
    client.logout();
    client.disconnect();
}

From source file:it.unimi.di.big.mg4j.document.DocumentCollectionTest.java

@BeforeClass
public static void setUp() throws IOException, ConfigurationException {
    // Create a new directory under /tmp
    tempDir = File.createTempFile("mg4jtest", null);
    tempDir.delete();//from w  ww.  ja v a  2  s . c  o  m
    tempDir.mkdir();
    // Now create the hierarchy for HTML files
    File htmlDir = new File(tempDir, "html");
    htmlDir.mkdir();
    System.err.println("Temporary directory: " + tempDir);
    htmlFileSet = new String[ndoc];
    for (int i = 0; i < ndoc; i++) {
        String docFile = new File(htmlDir, "doc" + i + ".html").toString();
        htmlFileSet[i] = docFile;
        Writer docWriter = new OutputStreamWriter(new FileOutputStream(docFile), "ISO-8859-1");
        docWriter.write(getHTMLDocument(document[i]));
        docWriter.close();
    }
    // Now create the mbox file
    Writer mboxWriter = new OutputStreamWriter(new FileOutputStream(new File(tempDir, "mbox")), "ISO-8859-1");
    for (int i = 0; i < ndoc; i++)
        mboxWriter.write(getMboxDocument(document[i]));
    mboxWriter.close();

    // Now create the zip collections
    FileSetDocumentCollection fileSetDocumentCollection = new FileSetDocumentCollection(htmlFileSet,
            new HtmlDocumentFactory(DEFAULT_PROPERTIES));
    ZipDocumentCollectionBuilder zipCollBuilder = new ZipDocumentCollectionBuilder(
            new File(tempDir, "zip").toString(), fileSetDocumentCollection.factory(), true);
    zipCollBuilder.build(fileSetDocumentCollection);

    ZipDocumentCollectionBuilder apprZipCollBuilder = new ZipDocumentCollectionBuilder(
            new File(tempDir, "azip").toString(), fileSetDocumentCollection.factory(), false);
    apprZipCollBuilder.build(fileSetDocumentCollection);
    fileSetDocumentCollection.close();

    // Now create the simple collections
    SimpleCompressedDocumentCollectionBuilder simpleCollBuilder = new SimpleCompressedDocumentCollectionBuilder(
            new File(tempDir, "simple").toString(), fileSetDocumentCollection.factory(), true);
    simpleCollBuilder.build(fileSetDocumentCollection);

    SimpleCompressedDocumentCollectionBuilder apprSimpleCollBuilder = new SimpleCompressedDocumentCollectionBuilder(
            new File(tempDir, "asimple").toString(), fileSetDocumentCollection.factory(), false);
    apprSimpleCollBuilder.build(fileSetDocumentCollection);
    fileSetDocumentCollection.close();
}

From source file:edu.brandeis.cs.planner.utils.WsdlClient.java

public static void copy(InputStream is, Writer writer) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line;/*  w  ww .  j a v a 2 s.  com*/
    while ((line = br.readLine()) != null)
        writer.write(line);
    br.close();
    is.close();
    writer.close();
}

From source file:IOUtil.java

/**
 * Copy chars from a <code>String</code> to a <code>Writer</code>.
 *//*  ww w.  j a  v  a  2 s.c om*/
public static void copy(final String input, final Writer output) throws IOException {
    output.write(input);
}

From source file:com.l2jfree.security.NewCipher.java

private static void reportSoCalledChecksum(ByteBuffer buf, int off, int size, long calc, long real) {
    @SuppressWarnings("resource")
    Writer w = null;//  www.ja va  2 s .  co  m
    try {
        w = new FileWriter("chk_facts.txt", true);
        if (buf == null)
            w.write("Checksum failed, size = " + size + "\r\n");
        else {
            w.write("Checksum C=" + calc + " R=" + real/* + "\r\n"*/);
            w.write(HexUtil.printData(buf, off, size));
            w.write("\r\n");
        }
    } catch (IOException e) {
        // ignore
    } finally {
        IOUtils.closeQuietly(w);
    }
}