Example usage for java.io StringWriter getBuffer

List of usage examples for java.io StringWriter getBuffer

Introduction

In this page you can find the example usage for java.io StringWriter getBuffer.

Prototype

public StringBuffer getBuffer() 

Source Link

Document

Return the string buffer itself.

Usage

From source file:com.flexive.shared.media.FxMetadata.java

/**
 * Get this metadata object as XML document
 *
 * @return XML document//from  w w  w  .ja v a2s .  com
 * @throws FxApplicationException on errors
 */
public String toXML() throws FxApplicationException {
    StringWriter sw = new StringWriter(2000);
    try {
        XMLStreamWriter writer = getXmlOutputFactory().createXMLStreamWriter(sw);
        writer.writeStartDocument();
        writer.writeStartElement("metadata");
        writer.writeAttribute("mediatype", getMediaType().name());
        writer.writeAttribute("mimetype", getMimeType());
        writer.writeAttribute("filename", getFilename());
        writeXMLTags(writer);
        for (FxMetadataItem mdi : getMetadata()) {
            final String value = mdi.getValue().replaceAll("[\\x00-\\x1F]", ""); //filter out control characters
            if (StringUtils.isEmpty(value))
                continue;
            writer.writeStartElement("meta");
            writer.writeAttribute("key", mdi.getKey());
            writer.writeCData(value);
            writer.writeEndElement();
        }
        writer.writeEndElement();
        writer.writeEndDocument();
        writer.flush();
        writer.close();
    } catch (XMLStreamException e) {
        throw new FxApplicationException(e, "ex.general.xml", e.getMessage());
    }
    return sw.getBuffer().toString();
}

From source file:com.qspin.qtaste.testsuite.impl.JythonTestScript.java

private String getThrowableDescription(Throwable e) {
    StringWriter descriptionWriter = new StringWriter();
    e.printStackTrace(new PrintWriter(descriptionWriter));
    int sunReflectPos = descriptionWriter.getBuffer().indexOf("\tat sun.reflect.");
    if (sunReflectPos != -1) {
        descriptionWriter.getBuffer().setLength(sunReflectPos);
    }/*from  w  w  w  .ja v a  2s .c o  m*/
    return descriptionWriter.toString();
}

From source file:com.aurel.track.lucene.util.openOffice.OOIndexer.java

/**
 * Get the string content of an xml file
 *///from   w w  w .java  2s.co m
public String parseXML(File file) {
    Document document = null;
    DocumentBuilderFactory documentBuilderfactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    try {
        builder = documentBuilderfactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        LOGGER.info("Building the document builder from factory failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        return null;
    }
    try {
        document = builder.parse(file);
    } catch (SAXException e) {
        LOGGER.info("Parsing the XML document " + file.getPath() + " failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    } catch (IOException e) {
        LOGGER.info("Reading the XML document " + file.getPath() + " failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    if (document == null) {
        return null;
    }
    StringWriter result = new StringWriter();
    Transformer transformer = null;
    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    } catch (TransformerConfigurationException e) {
        LOGGER.warn(
                "Creating the transformer failed with TransformerConfigurationException: " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        return null;
    }
    try {
        transformer.transform(new DOMSource(document), new StreamResult(result));
    } catch (TransformerException e) {
        LOGGER.warn("Transform failed with TransformerException: " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    return result.getBuffer().toString();
}

From source file:com.jaeksoft.searchlib.crawler.web.spider.HtmlArchiver.java

final private StringBuffer checkCSSContent(URL objectUrl, String css) throws ClientProtocolException,
        IllegalStateException, IOException, SearchLibException, URISyntaxException {
    StringWriter sw = null;
    PrintWriter pw = null;//w  ww. j a  va 2s.c  o  m

    try {
        NaiveCSSParser cssParser = new NaiveCSSParser();
        Collection<CSSRule> rules = cssParser.parseStyleSheet(css);
        if (rules == null)
            return null;
        if (rules.size() == 0)
            return null;
        sw = new StringWriter();
        pw = new PrintWriter(sw);
        for (CSSRule rule : rules) {
            if (rule instanceof CSSStyleRule) {
                handleCssStyle(objectUrl, (CSSStyleRule) rule);
            } else if (rule instanceof CSSImportRule) {
                CSSImportRule importRule = (CSSImportRule) rule;
                String newSrc = downloadObject(objectUrl, importRule.getHref(), "text/css");
                importRule.setHref(newSrc);
            }
        }
        cssParser.write(pw);
        return sw.getBuffer();
    } catch (IOException e) {
        Logging.warn("CSS ISSUE", e);
        return null;
    } finally {
        IOUtils.close(pw, sw);
    }
}

From source file:net.sf.jabref.EntryEditor.java

/**
 * If the entry has been just loaded or it has been changed, update the content of the BibTeX
 * panel with the new source./*from   w w w. ja  va2 s  . com*/
 */
public void updateSource() {
    if (shouldUpdateSourcePanel) {
        StringWriter sw = new StringWriter(200);
        try {
            LatexFieldFormatter formatter = new LatexFieldFormatter();
            formatter.setNeverFailOnHashes(true);
            entry.write(sw, formatter, false);

            String srcString = sw.getBuffer().toString();
            source.setText(srcString);
            lastAcceptedSourceString = srcString;

            //////////////////////////////////////////////////////////
            // Set the current Entry to be selected.
            // Fixes the bug of losing selection after, e.g.
            // an autogeneration of a BibTeX key.
            // - ILC (16/02/2010) -
            //////////////////////////////////////////////////////////
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    final int row = panel.mainTable.findEntry(entry);
                    if (row >= 0) {
                        if (panel.mainTable.getSelectedRowCount() == 0) {
                            panel.mainTable.setRowSelectionInterval(row, row);
                        }
                        panel.mainTable.ensureVisible(row);
                    }
                }
            });

        } catch (IOException ex) {
            source.setText(ex.getMessage() + "\n\n"
                    + Globals.lang("Correct the entry, and reopen editor to display/edit source."));
            source.setEditable(false);
        }
    }
}

From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentQCController.java

@RequestMapping("/expressionExperiment/outliersRemoved.html")
public ModelAndView identifyOutliersRemoved(Long id) throws IOException {

    if (id == null) {
        log.warn("No id!");
        return null;
    }//from   w w w.  j a  va 2 s.c  o  m

    ExpressionExperiment ee = expressionExperimentService.load(id);
    if (ee == null) {
        log.warn("Could not load experiment with id " + id);
        return null;
    }

    ee = expressionExperimentService.thawLite(ee);
    Collection<BioAssay> bioAssays = new HashSet<>();
    for (BioAssay assay : ee.getBioAssays()) {
        if (assay.getIsOutlier()) {
            bioAssays.add(assay);
        }
    }

    // and write it out
    StringWriter writer = new StringWriter();
    StringBuffer buf = writer.getBuffer();

    ExpressionDataWriterUtils.appendBaseHeader(ee, "Outliers removed", buf);

    ExperimentalDesignWriter edWriter = new ExperimentalDesignWriter();
    ee = expressionExperimentService.thawLiter(ee);
    edWriter.write(writer, ee, bioAssays, false, true);

    ModelAndView mav = new ModelAndView(new TextView());
    mav.addObject(TextView.TEXT_PARAM, buf.toString());
    return mav;
}

From source file:com.gdo.servlet.RpcWrapper.java

/**
 * Returns the stack trace of exception in fault.
 * /*w w  w  . ja  v  a2s .  co  m*/
 * @param stclContext
 *            the stencil context.
 * @param entry
 *            the RPC entry.
 * @param e
 *            the exception throwed.
 */
private void fault(StclContext stclContext, String entry, Exception e, RpcArgs args) {
    String content = "";
    StringWriter sw = new StringWriter();
    e.printStackTrace(new PrintWriter(sw));
    content += sw.getBuffer().toString();
    fault(stclContext, entry, content, args);
}

From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentQCController.java

@RequestMapping("/expressionExperiment/possibleOutliers.html")
public ModelAndView identifyPossibleOutliers(Long id) throws IOException {

    if (id == null) {
        log.warn("No id!");
        return null;
    }//from  w  w  w.  java  2  s .  com

    ExpressionExperiment ee = expressionExperimentService.load(id);
    if (ee == null) {
        log.warn("Could not load experiment with id " + id);
        return null;
    }

    // identify outliers
    if (!sampleCoexpressionAnalysisService.hasAnalysis(ee)) {
        log.warn("Experiment doesn't have correlation matrix computed (will not create right now)");
        return null;
    }

    DoubleMatrix<BioAssay, BioAssay> sampleCorrelationMatrix = sampleCoexpressionAnalysisService
            .loadFullMatrix(ee);
    if (sampleCorrelationMatrix == null || sampleCorrelationMatrix.rows() < 3) {
        return null;
    }

    Collection<OutlierDetails> outliers = outlierDetectionService
            .identifyOutliersByMedianCorrelation(sampleCorrelationMatrix);

    Collection<BioAssay> bioAssays = new HashSet<>();
    if (!outliers.isEmpty()) {
        for (OutlierDetails details : outliers) {
            bioAssays.add(details.getBioAssay());

        }
    }

    // and write it out
    StringWriter writer = new StringWriter();
    StringBuffer buf = writer.getBuffer();

    ExpressionDataWriterUtils.appendBaseHeader(ee, "Sample outlier", buf);

    ExperimentalDesignWriter edWriter = new ExperimentalDesignWriter();
    ee = expressionExperimentService.thawLiter(ee);
    edWriter.write(writer, ee, bioAssays, false, true);

    ModelAndView mav = new ModelAndView(new TextView());
    mav.addObject(TextView.TEXT_PARAM, buf.toString());
    return mav;
}

From source file:edu.ku.kuali.kra.award.web.struts.action.AwardActionsAction.java

/**
 * BU KC/SAP Integration: RDFD print functionality.
 *
 * @param mapping/*w  ww .  ja v a 2s.c o  m*/
 *            - The ActionMapping used to select this instance
 * @param form
 *            - The optional ActionForm bean for this request (if any)
 * @param request
 *            - The HTTP request we are processing
 * @param response
 *            - The HTTP response we are creating
 * @return an ActionForward instance describing where and how control should be forwarded, or null if the response has already been completed.
 * @throws Exception
 *             - if an exception occurs
 */
public ActionForward printAward(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    SapIntegrationService integrationService = KcServiceLocator.getService(SapIntegrationService.class);

    // call the transmit() method on SAPIntegrationService
    AwardForm awardForm = (AwardForm) form;
    Award primaryAward = awardForm.getAwardHierarchyBean().getRootNode().getAward();
    // cycle through the award list and only pass on those that have been
    // marked as approved for transmission
    ArrayList<Award> awardsList = new ArrayList<Award>();

    checkAwardChildren(awardForm.getAwardHierarchyBean().getRootNode(), awardsList, request);

    SapTransmission transmission = new SapTransmission(primaryAward, awardsList);
    String transmissionXml = integrationService.getTransmitXml(transmission);
    transmissionXml = StringUtils.replace(transmissionXml, "ns2:", "");

    StringReader xmlReader = new StringReader(transmissionXml);
    StreamSource xmlSource = new StreamSource(xmlReader);

    InputStream xslStream = this.getClass()
            .getResourceAsStream("/edu/bu/kuali/kra/printing/stylesheet/sapPrint.xslt");
    StreamSource xslSource = new StreamSource(xslStream);

    StringWriter resultWriter = new StringWriter();
    StreamResult result = new StreamResult(resultWriter);

    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer(xslSource);
    transformer.transform(xmlSource, result);

    PrintWriter out = response.getWriter();
    out.write(resultWriter.getBuffer().toString());

    return null;
}

From source file:org.auraframework.impl.adapter.ServletUtilAdapterImplUnitTest.java

@Test
public void testSend404() throws Exception {
    ServletUtilAdapterImpl sua = new ServletUtilAdapterImpl();
    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    ContextService contextService = Mockito.mock(ContextService.class);
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);

    sua.setContextService(contextService);

    Mockito.when(response.getWriter()).thenReturn(pw);

    sua.send404(null, null, response);//from  w  w  w .  ja  va2 s .  c o  m

    Mockito.verify(response, Mockito.times(1)).setStatus(HttpServletResponse.SC_NOT_FOUND);
    Mockito.verify(response, Mockito.times(1)).getWriter();
    Mockito.verify(contextService, Mockito.times(1)).endContext();
    Mockito.verifyNoMoreInteractions(response);
    Mockito.verifyNoMoreInteractions(contextService);

    String output = sw.getBuffer().toString();
    assertTrue("Output should start with '404 Not Found'", output.startsWith("404 Not Found"));
    assertTrue("Output should be longer than 256 bytes", output.length() > 256);
}