Example usage for java.io Writer append

List of usage examples for java.io Writer append

Introduction

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

Prototype

public Writer append(char c) throws IOException 

Source Link

Document

Appends the specified character to this writer.

Usage

From source file:com.github.rvesse.airline.help.html.HtmlCommandUsageGenerator.java

/**
 * Outputs the HTML header for the page//www . j  a va2  s  . co  m
 * 
 * @param writer
 *            Writer
 * @throws IOException
 */
protected void outputHtmlHeader(Writer writer) throws IOException {
    writer.append("<html>\n");
    writer.append("<head>\n");
    outputStylesheets(writer);
    writer.append("<style>\n");
    outputAdditionalCss(writer);
    writer.append("</style>\n");
    writer.append("</head>\n");
}

From source file:org.efaps.wikiutil.export.latex.MakePDF.java

/**
 * Writes the variables file.//  w  w  w .  ja v a  2s . c o  m
 *
 * @throws IOException if content file could not be written
 */
protected void writeVariablesFile() throws IOException {
    final File content = new File(this.tempDir, "variables.tex");
    Writer outp = null;
    try {
        outp = new FileWriter(content);
        for (final Map.Entry<String, String> varEntry : this.variables.entrySet()) {
            outp.append("\\newcommand{\\").append(varEntry.getKey()).append("}{").append(varEntry.getValue())
                    .append("}\n");
        }
    } finally {
        if (outp != null) {
            outp.close();
        }
    }
}

From source file:org.eclipse.skalli.services.extension.rest.ResourceRepresentation.java

@Override
public void write(Writer writer) throws IOException {
    if (object != null) {
        if (context == null) {
            writer.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); //$NON-NLS-1$
            XStream xstream = getXStream();
            if (compact) {
                xstream.marshal(object, new CompactWriter(writer));
            } else {
                xstream.toXML(object, writer);
            }//from   w  ww  .  ja  va 2s .  c o m
        } else if (converter.getConversionClass().isAssignableFrom(object.getClass())) {
            RestService restService = Services.getRequiredService(RestService.class);
            MediaType mediaType = context.getMediaType();
            if (!restService.isSupported(context)) {
                throw new IOException(MessageFormat.format("Unsupported media type ''{0}''", mediaType));
            }
            RestWriter restWriter = restService.getRestWriter(writer, context);
            String hrefQueryAttr = context.getQueryAttribute(LINKS_QUERY_ATTRIBUTE);
            if (RELATIVE_LINKS.equalsIgnoreCase(hrefQueryAttr)) {
                restWriter.set(RestWriter.RELATIVE_LINKS);
            }
            String membersQueryAttr = context.getQueryAttribute(MEMBERS_QUERY_ATTRIBUTE);
            if (ALL_MEMBERS.equalsIgnoreCase(membersQueryAttr)) {
                restWriter.set(RestWriter.ALL_MEMBERS);
            }
            try {
                converter.marshal(object, restWriter);
            } catch (RuntimeException e) {
                // don't trust the integrity of plugins!
                throw new IOException(
                        MessageFormat.format("Failed to write response for {0}", context.getPath()), e);
            } finally {
                restWriter.flush();
            }
        } else {
            throw new IOException("Failed to create resource representation");
        }
    }
}

From source file:won.preprocessing.MailProcessing.java

/**
 * Read mail files from the input folder, extract several fields (e.g. subject, content, from,
 * to) and save this data back into a text file of the output folder.
 *
 * @param inputFolder  input folder with the mails
 * @param outputFolder output folder with extracted content files
 * @throws IOException//from w ww .ja v a2 s .  co m
 */
private static void preprocessMails(String inputFolder, String outputFolder) throws IOException {

    File inFolder = new File(inputFolder);
    File outFolder = new File(outputFolder);
    outFolder.mkdirs();

    if (!inFolder.isDirectory()) {
        throw new IOException("Input folder not a directory: " + inputFolder);
    }
    if (!outFolder.isDirectory()) {
        throw new IOException("Output folder not a directory: " + outputFolder);
    }

    logger.info("preprocessing mail files: ");
    logger.info("- input folder {}", inputFolder);
    logger.info("- output folder {}", outputFolder);

    for (File file : inFolder.listFiles()) {
        if (file.isDirectory()) {
            continue;
        }

        logger.debug("processing mail file: {} ", file);
        FileInputStream fis = null;
        Writer fw = null;

        try {
            fis = new FileInputStream(file);
            MimeMessage emailMessage = new MimeMessage(null, fis);
            MimeMessageParser parser = new MimeMessageParser(emailMessage);
            parser.parse();
            String content = null;
            if (parser.hasPlainContent()) {
                content = parser.getPlainContent();
                int endIndex = content.indexOf("-------------");
                if (endIndex != -1) {
                    content = content.substring(0, endIndex);
                }
            } else {
                logger.warn("no plain content in file: {}, use HTML content", file);
                content = parser.getHtmlContent();
            }

            File outfile = new File(outputFolder + "/" + file.getName());
            logger.debug("writing output file: {}", outfile.getAbsolutePath());
            logger.debug("- mail subject: {}", parser.getSubject());
            FileOutputStream outputStream = new FileOutputStream(outfile);

            // Enforce UTF-8 when writing files. Non UTF-8 files will be reported.
            fw = new OutputStreamWriter(outputStream, Charset.forName("UTF-8"));

            fw.append(FROM_PREFIX + parser.getFrom() + "\n");
            fw.append(TO_PREFIX + parser.getTo() + "\n");
            fw.append(DATE_PREFIX + emailMessage.getSentDate() + "\n");
            fw.append(SUBJECT_PREFIX + parser.getSubject() + "\n");
            fw.append(CONTENT_PREFIX + /*parser.getPlainContent()*/content + "\n");

        } catch (MessagingException me) {
            logger.error("Error opening mail file: " + file.getAbsolutePath(), me);
        } catch (IOException ioe) {
            logger.error("Error writing file: " + file.getAbsolutePath(), ioe);
            System.err.println("Error writing file: " + file.getAbsolutePath());
        } catch (Exception e) {
            logger.error("Error parsing mail file: " + file.getAbsolutePath(), e);
        } finally {
            if (fis != null)
                fis.close();
            if (fw != null)
                fw.close();
        }
    }
}

From source file:wsattacker.plugin.dos.dosExtension.result.ResultGenerator.java

private void saveResponseTime(Writer writer, List<LogEntryRequest> responseTimes) throws IOException {
    for (LogEntryRequest logEntry : responseTimes) {
        writer.append(String.valueOf(logEntry.getTsReceived())); // TsSend
        writer.append(',');
        writer.append(String.valueOf(logEntry.getTsSend())); // TsReceived
        writer.append(',');
        writer.append(String.valueOf(logEntry.getDuration())); // duration
        writer.append(',');
        // thread Number
        writer.append(String.valueOf(logEntry.getThreadNumber()));
        writer.append(',');
        writer.append(String.valueOf(logEntry.getFaultFlag())); // FaultFlag
        writer.append(',');
        writer.append(String.valueOf(logEntry.getErrorFlag())); // ErrorFlag
        writer.append(',');
        writer.append(String.valueOf(logEntry.getResponseStringCsv())); // response
        writer.append('\n');
    }/*from   w w w .  j  a v  a2 s  .c o m*/
}

From source file:ddf.catalog.transformer.xml.XmlResponseQueueTransformer.java

@Override
public BinaryContent transform(SourceResponse response, Map<String, Serializable> args)
        throws CatalogTransformerException {
    try {/*from   w w w .j av  a2s  .co  m*/
        Writer stringWriter = new StringWriter(BUFFER_SIZE);
        stringWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");

        MetacardPrintWriter writer = new MetacardPrintWriter(stringWriter);

        writer.startNode("metacards");
        for (Map.Entry<String, String> nsRow : NAMESPACE_MAP.entrySet()) {
            writer.addAttribute(nsRow.getKey(), nsRow.getValue());
        }

        if (response.getResults() != null && !response.getResults().isEmpty()) {
            StringWriter metacardContent = fjp.invoke(new MetacardForkTask(
                    ImmutableList.copyOf(response.getResults()), fjp, geometryTransformer, threshold));

            writer.setRawValue(metacardContent.getBuffer().toString());
        }

        writer.endNode(); // metacards

        ByteArrayInputStream bais = new ByteArrayInputStream(stringWriter.toString().getBytes());

        return new BinaryContentImpl(bais, MIME_TYPE);
    } catch (Exception e) {
        LOGGER.info("Failed Query response transformation", e);
        throw new CatalogTransformerException("Failed Query response transformation");
    }
}

From source file:com.bstek.dorado.view.output.ClientEventListenersOutputter.java

protected void outputListener(ClientEvent listener, OutputContext context) throws IOException {
    JsonBuilder json = context.getJsonBuilder();
    Writer writer = context.getWriter();
    String signature;/* w  w  w .j  a  v a  2 s  . com*/
    if (listener instanceof DynaSignatureClientEvent) {
        signature = StringUtils.defaultIfEmpty(((DynaSignatureClientEvent) listener).getSignature(),
                DEFAULT_SIGNATURE);
    } else {
        signature = DEFAULT_SIGNATURE;
    }

    if (DEFAULT_SIGNATURE.equals(signature)) {
        json.beginValue();
        writer.append("function(").append(signature).append("){\n").append(listener.getScript()).append("\n}");
        json.endValue();
    } else {
        json.object().key("fn").beginValue();
        writer.append("function(").append(signature).append("){\n").append(listener.getScript()).append("\n}");
        json.endValue();
        json.key("options").object().key("autowire").value(true).endObject();
        json.endObject();
    }
}

From source file:com.stevpet.sonar.plugins.dotnet.resharper.profiles.ReSharperProfileExporter.java

private void printRule(Writer writer, ReSharperRule resharperRule) throws IOException {
    // This is generally what the output will look like:
    //        <IssueType Id="ClassNeverInstantiated.Global"
    //                   Enabled="True"
    //                   Description="Class is never instantiated: Non-private accessibility"
    //                   Severity="SUGGESTION" />

    writer.append("    <IssueType");
    writer.append(" Id=\"");
    StringEscapeUtils.escapeXml(writer, resharperRule.getId());

    writer.append("\" Enabled=\"");
    StringEscapeUtils.escapeXml(writer, String.valueOf(resharperRule.isEnabled()));

    String category = resharperRule.getCategory();
    if (category != null && !StringUtils.isBlank(category)) {
        writer.append("\" Category=\"");
        StringEscapeUtils.escapeXml(writer, category);
    }// ww  w  .  j ava  2s.c o  m

    String wiki = resharperRule.getWikiLink();
    if (wiki != null && !StringUtils.isBlank(wiki)) {
        writer.append("\" WikiUrl=\"");
        StringEscapeUtils.escapeXml(writer, wiki);
    }

    writer.append("\" Description=\"");
    StringEscapeUtils.escapeXml(writer, resharperRule.getDescription());
    writer.append("\" Severity=\"");
    StringEscapeUtils.escapeXml(writer, resharperRule.getSeverity().toString());
    writer.append("\"/>\n");
}

From source file:com.amalto.core.storage.record.DataRecordDefaultWriter.java

public void write(DataRecord record, Writer writer) throws IOException {
    boolean isReferenceField;
    writer.write("<result>\n"); //$NON-NLS-1$
    for (FieldMetadata fieldMetadata : record.getSetFields()) {
        if (delegator.hide(fieldMetadata)) {
            continue;
        }//w w w  .  jav a 2 s  .c om
        Object value = record.get(fieldMetadata);
        if (value != null) {
            String name = fieldMetadata.getName();
            writer.append("\t<").append(name).append(">"); //$NON-NLS-1$ //$NON-NLS-2$
            isReferenceField = fieldMetadata instanceof ReferenceFieldMetadata;
            if (value instanceof Object[]) {
                Object[] values = (Object[]) value;
                for (Object currentValue : values) {
                    if (isReferenceField) {
                        writer.append("[").append(StringEscapeUtils.escapeXml(String.valueOf(currentValue))) //$NON-NLS-1$
                                .append("]"); //$NON-NLS-1$
                    } else {
                        writer.append(StringEscapeUtils.escapeXml(String.valueOf(currentValue)));
                    }
                }
            } else {
                if (isReferenceField) {
                    writer.append("[").append(StringEscapeUtils.escapeXml(String.valueOf(value))).append("]"); //$NON-NLS-1$ //$NON-NLS-2$
                } else {
                    writer.append(
                            StringEscapeUtils.escapeXml(StorageMetadataUtils.toString(value, fieldMetadata)));
                }
            }
            writer.append("</").append(name).append(">\n"); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }
    writer.append("</result>"); //$NON-NLS-1$
    writer.flush();
}

From source file:com.adrguides.model.Guide.java

private void saveTextToFile(File f, String text) throws IOException {

    Writer filewriter = null;
    try {/*from   ww w . ja  v  a2s . c  om*/
        filewriter = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
        filewriter.append(text);
    } finally {
        if (filewriter != null) {
            try {
                filewriter.close();
            } catch (IOException e) {
            }
        }
    }
}