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:org.xwoot.xwootApp.web.servlets.Information.java

/**
 * {@inheritDoc}/*from  ww w  .  j a  v a  2s.  co  m*/
 * 
 * @see HttpServlet#service(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
 */
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        response.setContentType("text/xml; charset=UTF-8");
        StringBuffer result = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        XWootSite woot = XWootSite.getInstance();
        String info = request.getParameter("request");
        if (info == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            result.append("<error>No specific information requested</error>");
        } else if (info.equals("isXWootInitialized")) {
            result.append("<initialized>" + woot.isStarted() + "</initialized>");
        } else {
            if (!woot.isStarted()) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                result.append("<error>Server not started yet</error>");
            } else {
                XWootAPI xwoot = woot.getXWootEngine();
                if (info.equals("isWikiConnected")) {
                    result.append("<wikiConnected>" + xwoot.isContentManagerConnected() + "</wikiConnected>");
                } else if (info.equals("isP2PNetworkConnected")) {
                    result.append("<p2pConnected>" + xwoot.isConnectedToP2PNetwork() + "</p2pConnected>");
                } else if (info.equals("isDocumentManaged")) {
                    String pagename = request.getParameter("document");
                    if (StringUtils.isEmpty(pagename)) {
                        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                        result.append("<error>You must specify a page name</error>");
                    } else {
                        /*   XWootPage page = new XWootPage(pagename, null);
                           result.append("<managed name=\"" + pagename + "\">" + ((XWoot)xwoot).isPageManaged(page)
                        + "</managed>");*/
                    }
                } else if (info.equals("listPeers")) {
                    result.append("<peers>\n");
                    for (Object peer : xwoot.getNeighborsList()) {
                        result.append("  <peer connected=\"" + getConnectionStatus(peer) + "\">" + peer
                                + "</peer>\n");
                    }
                    result.append("</peers>");
                } else if (info.equals("listLastPages")) {
                    String id = request.getParameter("id");
                    List<String> pages = xwoot.getLastPages(id);
                    result.append("<pages>\n");
                    for (String pageName : pages) {
                        result.append("  <page>" + pageName + "</page>\n");
                    }
                    result.append("</pages>\n");
                } else {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    result.append("<error>Unknown information</error>");
                    System.out.println(info);
                }
            }
        }
        String resultString = result.toString();
        Writer out = response.getWriter();
        response.setContentLength(resultString.getBytes("UTF-8").length);
        out.append(resultString);
        out.close();
    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:com.github.rwitzel.streamflyer.core.ModifiableWriterUnitTest.java

/**
 * Asserts that the content of the character buffer is never bigger than the newNumberOfChars plus the look-behind.
 * Additionally asserts that the capacity of the character buffer does not exceed twice the size of
 * newNumberOfChars.//from  w  w  w. j  a v a2  s . co m
 * 
 * @param minimumLengthOfLookBehind
 * @param newNumberOfChars
 * @param numberOfCharactersToSkip
 * @param sizeOfInput
 * @param bufferSize
 * @throws Exception
 */
private void assertCharacterBufferDoesNotExceedRequestedLength(int minimumLengthOfLookBehind,
        int newNumberOfChars, int numberOfCharactersToSkip, int sizeOfInput, int bufferSize) throws Exception {

    // setup: create modifier and reader
    IdleModifier modifier = new IdleModifier(minimumLengthOfLookBehind, newNumberOfChars,
            numberOfCharactersToSkip);
    ModifyingWriter writer = new ModifyingWriter(new NullWriter(), modifier);
    Writer bufferedWriter = new BufferedWriter(writer, bufferSize);

    // read the stream into an output stream
    for (int index = 0; index < sizeOfInput; index++) {
        bufferedWriter.append('a');
    }
    writer.flush();
    writer.close();

    assertTrue(
            "max requested length of character buffer "
                    + modifier.getFactory().getMaxRequestedNewNumberOfChars() + " should be smaller than "
                    + newNumberOfChars + " but was not",
            modifier.getFactory().getMaxRequestedNewNumberOfChars() <= newNumberOfChars);

    assertTrue("max size of character buffer " + modifier.getMaxSizeOfCharacterBuffer()
            + " should be smaller than " + (minimumLengthOfLookBehind + newNumberOfChars) + " but was not",
            modifier.getMaxSizeOfCharacterBuffer() <= minimumLengthOfLookBehind + newNumberOfChars);

    // as we know that StringBuilder.ensureCapacity(int) doubles the input
    // size if appropriate, we test for (look-behind + numChars) * 2
    assertTrue("max capacity of character buffer " + modifier.getMaxCapacityOfCharacterBuffer()
            + " should be smaller than " + (minimumLengthOfLookBehind + newNumberOfChars) * 2 + " but was not",
            modifier.getMaxCapacityOfCharacterBuffer() <= (minimumLengthOfLookBehind + newNumberOfChars) * 2);
}

From source file:no.uis.service.studinfo.commons.StudinfoValidator.java

protected List<String> validate(String studieinfoXml, StudinfoType infoType, int year, FsSemester semester,
        String language) throws Exception {

    // save xml/* w w  w  .j a  va 2  s.c om*/
    File outFile = new File("target/out", infoType.toString() + year + semester + language + ".xml");
    if (outFile.exists()) {
        outFile.delete();
    } else {
        outFile.getParentFile().mkdirs();
    }
    File outBackup = new File("target/out", infoType.toString() + year + semester + language + "_orig.xml");
    Writer backupWriter = new OutputStreamWriter(new FileOutputStream(outBackup), IOUtils.UTF8_CHARSET);
    backupWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    IOUtils.copy(new StringReader(studieinfoXml), backupWriter, IOBUFFER_SIZE);
    backupWriter.flush();
    backupWriter.close();

    TransformerFactory trFactory = TransformerFactory.newInstance();
    Source schemaSource = new StreamSource(getClass().getResourceAsStream("/fspreprocess.xsl"));
    Transformer stylesheet = trFactory.newTransformer(schemaSource);

    Source input = new StreamSource(new StringReader(studieinfoXml));

    Result result = new StreamResult(outFile);
    stylesheet.transform(input, result);

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(true);

    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = schemaFactory
            .newSchema(new Source[] { new StreamSource(new File("src/main/xsd/studinfo.xsd")) });

    factory.setSchema(schema);

    SAXParser parser = factory.newSAXParser();

    XMLReader reader = parser.getXMLReader();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler(infoType, year, semester, language);
    reader.setErrorHandler(errorHandler);
    reader.setContentHandler(errorHandler);
    try {
        reader.parse(
                new InputSource(new InputStreamReader(new FileInputStream(outFile), IOUtils.UTF8_CHARSET)));
    } catch (SAXException ex) {
        // do nothing. The error is handled in the error handler
    }
    return errorHandler.getMessages();
}

From source file:org.openqa.selenium.firefox.Preferences.java

public void writeTo(Writer writer) throws IOException {
    for (Map.Entry<String, Object> pref : allPrefs.entrySet()) {
        writer.append("user_pref(\"").append(pref.getKey()).append("\", ");
        writer.append(valueAsPreference(pref.getValue()).replaceAll("\\\\", "\\\\\\\\"));
        writer.append(");\n");
    }/* w  w  w . ja  va2  s.c  om*/
}

From source file:com.echosource.ada.rules.AdaProfileExporter.java

private void appendModule(Writer writer, ActiveRule activeRule, boolean manyInstances) throws IOException {
    String moduleName = StringUtils.substringAfterLast(activeRule.getConfigKey(), "/");
    writer.append("<module name=\"");
    StringEscapeUtils.escapeXml(writer, moduleName);
    writer.append("\">");
    if (manyInstances) {
        appendModuleProperty(writer, "id", activeRule.getRuleKey());
    }/*  w ww.  ja  v a2  s  .c o m*/
    appendModuleProperty(writer, "severity", AdaRulePriorityMapper.to(activeRule.getPriority()));
    appendRuleParameters(writer, activeRule);
    writer.append("</module>");
}

From source file:org.drools.planner.benchmark.statistic.calculatecount.CalculateCountStatistic.java

private CharSequence writeCsvStatistic(File solverStatisticFilesDirectory, String baseName) {
    List<CalculateCountScvLine> csvLineList = extractCsvLineList();
    File csvStatisticFile = new File(solverStatisticFilesDirectory, baseName + "CalculateCountStatistic.csv");
    Writer writer = null;
    try {//from   w  ww  .jav a 2  s. c o m
        writer = new OutputStreamWriter(new FileOutputStream(csvStatisticFile), "utf-8");
        writer.append("\"TimeMillisSpend\"");
        for (String configName : configNameList) {
            writer.append(",\"").append(configName.replaceAll("\\\"", "\\\"")).append("\"");
        }
        writer.append("\n");
        for (CalculateCountScvLine line : csvLineList) {
            writer.write(Long.toString(line.getTimeMillisSpend()));
            for (String configName : configNameList) {
                writer.append(",");
                Long calculateCountPerSecond = line.getConfigNameToCalculateCountPerSecondMap().get(configName);
                if (calculateCountPerSecond != null) {
                    writer.append(calculateCountPerSecond.toString());
                }
            }
            writer.append("\n");
        }
    } catch (IOException e) {
        throw new IllegalArgumentException("Problem writing csvStatisticFile: " + csvStatisticFile, e);
    } finally {
        IOUtils.closeQuietly(writer);
    }
    return "  <p><a href=\"" + csvStatisticFile.getName() + "\">CVS file</a></p>\n";
}

From source file:it.geosolutions.geobatch.migrationmonitor.monitor.MonitorAction.java

@Override
public Queue<FileSystemEvent> execute(Queue<FileSystemEvent> events) throws ActionException {

    // return object
    final Queue<FileSystemEvent> outputEvents = new LinkedList<FileSystemEvent>();

    try {/*from w w w  .  ja va 2 s.c  om*/
        // looking for file
        if (events.size() == 0)
            throw new IllegalArgumentException(
                    "MonitorAction::execute(): Wrong number of elements for this action: " + events.size());

        listenerForwarder.setTask("config");
        listenerForwarder.started();

        if (configuration == null) {
            final String message = "MonitorAction::execute(): DataFlowConfig is null.";
            if (LOGGER.isErrorEnabled())
                LOGGER.error(message);
            throw new IllegalStateException(message);
        }

        // retrieve all the ELEMENTS table from the DB
        List<MigrationMonitor> migrationList = migrationMonitorDAO.findTablesToMigrate();
        DS2DSTokenResolver tknRes = null;

        // init some usefull counters
        int failsCounter = 0;
        int iterCounter = 0;
        int totElem = migrationList.size();

        // Process all MigrationMonitors retrieved
        for (MigrationMonitor mm : migrationList) {
            iterCounter++;
            try {
                tknRes = new DS2DSTokenResolver(mm, getConfigDir());
            } catch (IOException e) {
                failsCounter++;
                LOGGER.error(e.getMessage(), e);
                LOGGER.error("error while processing MigrationMonitor " + mm.toString()
                        + " let's skip it! (the error happens while resolving tokens...)");
                LOGGER.error("fail number: " + failsCounter + " MigrationMonitor processed " + iterCounter + "/"
                        + totElem);
                continue;
            }

            String filename = getTempDir() + File.separator + mm.getTableName() + mm.getLayerId() + ".xml";
            Writer writer = null;
            try {
                writer = new FileWriter(filename);
                writer.append(tknRes.getOutputFileContent());
            } catch (IOException e) {
                LOGGER.error("error while processing MigrationMonitor " + mm.toString()
                        + " let's skip it! (the error happens while writing on the output file)");
                LOGGER.error("fail number: " + failsCounter + " MigrationMonitor processed " + iterCounter + "/"
                        + totElem);
                continue;
            } finally {
                try {
                    writer.close();
                    FileSystemEvent fse = new FileSystemEvent(new File(filename),
                            FileSystemEventType.FILE_ADDED);
                    outputEvents.add(fse);
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }

            mm.setMigrationStatus(MigrationStatus.INPROGRESS.toString().toUpperCase());
            migrationMonitorDAO.merge(mm);
        }

    } catch (Exception t) {
        final String message = "MonitorAction::execute(): " + t.getLocalizedMessage();
        if (LOGGER.isErrorEnabled())
            LOGGER.error(message, t);
        final ActionException exc = new ActionException(this, message, t);
        listenerForwarder.failed(exc);
        throw exc;
    }

    return outputEvents;
}

From source file:com.joliciel.csvLearner.features.BestFeatureFinder.java

public void writeBestFeatures(Writer writer, Map<String, Collection<NameValuePair>> bestFeatures) {
    try {// w  w w. j a  va2s  .c  o m
        for (Entry<String, Collection<NameValuePair>> entry : bestFeatures.entrySet()) {
            writer.append(CSVFormatter.format(entry.getKey()) + ",");
            for (NameValuePair pair : entry.getValue()) {
                if (!pair.getName().equals(TOTAL_ENTROPY))
                    writer.append(CSVFormatter.format(pair.getName()) + ",");
                writer.append(CSVFormatter.format(pair.getValue()) + ",");
            }
            writer.append("\n");
            writer.flush();
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:com.bstek.dorado.view.ViewOutputter.java

public void outputView(View view, OutputContext context) throws Exception {
    View originalView = context.getCurrentView();
    context.setCurrentView(view);//from  w  w w  .j a v  a 2  s .c  om

    DoradoContext doradoContext = DoradoContext.getCurrent();

    JexlContext jexlContext = null;
    Definition resourceRelativeDefinition = null;
    ViewConfig viewConfig = view.getViewConfig();
    if (viewConfig != null) {
        Map<String, Object> viewContext = DoradoContextUtils.getViewContextByBindingObject(doradoContext,
                viewConfig);
        DoradoContextUtils.pushNewViewContext(doradoContext, viewContext);

        ViewConfigDefinition viewConfigDefinition = (ViewConfigDefinition) BeanExtender
                .getExProperty(viewConfig, "viewConfigDefinition");
        if (viewConfigDefinition != null) {
            ExpressionHandler expressionHandler = (ExpressionHandler) doradoContext
                    .getServiceBean("expressionHandler");
            jexlContext = expressionHandler.getJexlContext();
            resourceRelativeDefinition = (Definition) jexlContext
                    .get(ViewConfigDefinition.RESOURCE_RELATIVE_DEFINITION);
            jexlContext.set(ViewConfigDefinition.RESOURCE_RELATIVE_DEFINITION, viewConfigDefinition);
        }
    }

    Writer writer = context.getWriter();
    context.createJsonBuilder();
    try {
        writer.append("var view=");
        super.output(view, context);
        writer.append(";\n");

        writer.append("function f(view){").append("view.set(\"children\",");
        childrenComponentOutputter.output(view.getChildren(), context);
        writer.append(");");

        String javaScriptFiles = view.getJavaScriptFile();
        if (StringUtils.isNotEmpty(javaScriptFiles)) {
            for (String file : StringUtils.split(javaScriptFiles, ";,")) {
                if (StringUtils.isNotEmpty(file)) {
                    Resource resource = doradoContext.getResource(file);
                    JavaScriptContent content = (JavaScriptContent) javaScriptResourceManager
                            .getContent(resource);
                    if (content.getIsController()) {
                        javaScriptResourceManager.outputContent(context, content);
                    } else {
                        context.addJavaScriptContent(content);
                    }
                }
            }
        }

        String styleSheetFiles = view.getStyleSheetFile();
        if (StringUtils.isNotEmpty(styleSheetFiles)) {
            for (String file : StringUtils.split(styleSheetFiles, ",;")) {
                if (StringUtils.isNotEmpty(file)) {
                    Resource resource = doradoContext.getResource(file);
                    Object content = styleSheetResourceManager.getContent(resource);
                    context.addStyleSheetContent(content);
                }
            }
        }

        writer.append("}\n");

        // DataType
        outputIncludeDataTypes(view, context);

        String exPackages = view.getPackages();
        if (StringUtils.isNotEmpty(exPackages)) {
            for (String pkg : StringUtils.split(exPackages, ",;")) {
                if (StringUtils.isNotEmpty(pkg)) {
                    context.addDependsPackage(pkg);
                }
            }
        }

        writer.append("f(view);\n");
    } finally {
        context.restoreJsonBuilder();
        context.setCurrentView(originalView);

        if (jexlContext != null) {
            jexlContext.set(ViewConfigDefinition.RESOURCE_RELATIVE_DEFINITION, resourceRelativeDefinition);
        }

        if (viewConfig != null) {
            DoradoContextUtils.popViewContext(doradoContext);
        }
    }
}

From source file:com.mail163.email.mail.transport.Rfc822Output.java

/**
 * Write a single attachment and its payload
 *///  ww  w .j  a  va2  s .  c om
private static void writeOneAttachment(Context context, Writer writer, OutputStream out, Attachment attachment)
        throws IOException, MessagingException {
    //       String attachmentName = attachment.mFileName;
    String attachmentName = EncoderUtil.encodeAddressDisplayName(attachment.mFileName);

    writeHeader(writer, "Content-Type", attachment.mMimeType + ";\n name=\"" + attachmentName + "\"");

    writeHeader(writer, "Content-Transfer-Encoding", "base64");
    // Most attachments (real files) will send Content-Disposition.  The suppression option
    // is used when sending calendar invites.
    if ((attachment.mFlags & Attachment.FLAG_ICS_ALTERNATIVE_PART) == 0) {
        writeHeader(writer, "Content-Disposition", "attachment;" + "\n filename=\"" + attachmentName + "\";"
                + "\n size=" + Long.toString(attachment.mSize));
    }

    writeHeader(writer, "Content-ID", attachment.mContentId);
    writer.append("\r\n");

    // Set up input stream and write it out via base64
    InputStream inStream = null;
    try {
        // Use content, if provided; otherwise, use the contentUri
        if (attachment.mContentBytes != null) {
            inStream = new ByteArrayInputStream(attachment.mContentBytes);
        } else {
            // try to open the file
            Uri fileUri = Uri.parse(attachment.mContentUri);
            inStream = context.getContentResolver().openInputStream(fileUri);
        }
        // switch to output stream for base64 text output
        writer.flush();
        Base64OutputStream base64Out = new Base64OutputStream(out, Base64.CRLF | Base64.NO_CLOSE);
        // copy base64 data and close up
        IOUtils.copy(inStream, base64Out);
        base64Out.close();

        // The old Base64OutputStream wrote an extra CRLF after
        // the output.  It's not required by the base-64 spec; not
        // sure if it's required by RFC 822 or not.
        out.write('\r');
        out.write('\n');
        out.flush();
    } catch (FileNotFoundException fnfe) {
        // Ignore this - empty file is OK
    } catch (IOException ioe) {
        throw new MessagingException("Invalid attachment.", ioe);
    }
}