Example usage for java.io StringWriter close

List of usage examples for java.io StringWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closing a StringWriter has no effect.

Usage

From source file:com.day.cq.wcm.foundation.TableTest.java

private void checkTable(Table table, String expectedFile) throws IOException {
    StringWriter w = new StringWriter();
    table.toHtml(w);/*from   w w w .  j av  a 2  s . com*/
    w.close();
    String expected = IOUtils.toString(getClass().getResourceAsStream(expectedFile), "utf-8");
    expected = expected.trim();
    String result = w.toString().trim();

    // unify line breaks
    expected = StringUtils.join(StringUtils.split(expected, "\r\n"), '\n');
    result = StringUtils.join(StringUtils.split(result, "\r\n"), '\n');
    assertEquals(expectedFile, expected, result);
}

From source file:org.easyrec.service.web.impl.DisplayServiceImpl.java

public String displayXml(String xml) {

    logger.debug(xml);//from  w w w  . ja v a  2  s  .  c  o m
    String table = null;
    if (xml != null) {
        try {
            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);
            displayTransformer.transform(new StreamSource(new StringReader(xml.trim())), result);
            sw.close();
            table = sw.toString();
        } catch (Exception e) {
            logger.debug("Error transforming xml for display!" + e);
        }
    }
    return table;
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.DeletePageController.java

public void doDeletePage(String pageUri, VitroRequest vreq, HttpServletResponse resp) {

    OntModel displayModel = getDisplayModel(vreq);
    if (displayModel == null) {
        //Throw some kind of exception
        log.error("Display model not being retrieved correctly");
    }//from   w w w. ja v a2 s.  c  o m

    String errorMessage = "";
    processDelete(pageUri, displayModel, vreq);

    //Edits to model occur here
    displayModel.enterCriticalSection(Lock.WRITE);
    try {
        log.debug("Statement to be removed are ");
        StringWriter r = new StringWriter();
        removeStatements.write(r, "N3");
        log.debug(r.toString());
        r.close();
        displayModel.remove(removeStatements);

    } catch (Exception ex) {
        log.error("An error occurred in processing command", ex);
        errorMessage += "An error occurred and the operation could not be completed successfully.";
    } finally {
        displayModel.leaveCriticalSection();
    }
}

From source file:schemacrawler.integration.test.SchemaSerializationTest.java

@Test
public void schemaSerializationWithXStream() throws Exception {
    final SchemaCrawlerOptions schemaCrawlerOptions = new SchemaCrawlerOptions();
    schemaCrawlerOptions.setSchemaInfoLevel(SchemaInfoLevelBuilder.maximum());

    final Catalog catalog = getCatalog(schemaCrawlerOptions);
    assertNotNull("Could not obtain catalog", catalog);
    assertTrue("Could not find any schemas", catalog.getSchemas().size() > 0);

    final Schema schema = catalog.lookupSchema("PUBLIC.BOOKS").orElse(null);
    assertNotNull("Could not obtain schema", schema);
    assertEquals("Unexpected number of tables in the schema", 6, catalog.getTables(schema).size());

    XmlSerializedCatalog xmlCatalog;/*  w w  w. j av  a  2 s.co m*/
    StringWriter writer;

    xmlCatalog = new XmlSerializedCatalog(catalog);
    writer = new StringWriter();
    xmlCatalog.save(writer);
    writer.close();
    final String xmlSerializedCatalog1 = writer.toString();
    assertNotNull("Catalog was not serialized to XML", xmlSerializedCatalog1);
    assertNotSame("Catalog was not serialized to XML", 0, xmlSerializedCatalog1.trim().length());

    xmlCatalog = new XmlSerializedCatalog(new StringReader(xmlSerializedCatalog1));
    final Catalog deserializedCatalog = xmlCatalog;
    assertNotNull("No database deserialized", deserializedCatalog);
    final Schema deserializedSchema = deserializedCatalog.lookupSchema("PUBLIC.BOOKS").orElse(null);
    assertNotNull("Could not obtain deserialized schema", deserializedSchema);
    assertEquals("Unexpected number of tables in the deserialized schema", 6,
            catalog.getTables(deserializedSchema).size());

    writer = new StringWriter();
    xmlCatalog.save(writer);
    writer.close();
    final String xmlSerializedCatalog2 = writer.toString();
    assertNotNull("Catalog was not serialized to XML", xmlSerializedCatalog2);
    assertNotSame("Catalog was not serialized to XML", 0, xmlSerializedCatalog2.trim().length());

    final DetailedDiff xmlDiff = new DetailedDiff(new Diff(xmlSerializedCatalog1, xmlSerializedCatalog2));
    final List<?> allDifferences = xmlDiff.getAllDifferences();
    if (!xmlDiff.similar()) {
        IOUtils.write(xmlSerializedCatalog1,
                new PrintWriter("serialized-schema-1.xml", StandardCharsets.UTF_8.name()));
        IOUtils.write(xmlSerializedCatalog2,
                new PrintWriter("serialized-schema-2.xml", StandardCharsets.UTF_8.name()));
    }
    assertEquals(xmlDiff.toString(), 0, allDifferences.size());
}

From source file:org.kalypso.ui.editorLauncher.GisMapEditorTemplateLauncher.java

/**
 * @see org.kalypso.ui.editorLauncher.IDefaultTemplateLauncher#createInput(org.eclipse.core.resources.IFile)
 *//*from   w ww  . java 2s  .  c o  m*/
@Override
public IEditorInput createInput(final IFile file) throws CoreException {
    final org.kalypso.template.gismapview.ObjectFactory gisMapFactory = new org.kalypso.template.gismapview.ObjectFactory();
    final JAXBContext jc = JaxbUtilities.createQuiet(org.kalypso.template.gismapview.ObjectFactory.class);

    try {
        if ("gml".equalsIgnoreCase(file.getProjectRelativePath().getFileExtension())) //$NON-NLS-1$
            throw new CoreException(StatusUtilities.createWarningStatus(
                    Messages.getString("org.kalypso.ui.editorLauncher.GisMapEditorTemplateLauncher.3"))); //$NON-NLS-1$

        final StyledLayerType layer = new ObjectFactory().createStyledLayerType();
        LayerTypeUtilities.initLayerType(layer, file, null);
        layer.setVisible(true);
        layer.setName(file.getName());
        layer.setFeaturePath("featureMember"); //$NON-NLS-1$

        final Layers layers = gisMapFactory.createGismapviewLayers();
        final JAXBElement<StyledLayerType> layerType = TemplateUtilities.OF_GISMAPVIEW.createLayer(layer);

        layers.getLayer().add(layerType);
        layers.setActive(layer);

        final ExtentType extent = new ObjectFactory().createExtentType();
        extent.setRight(0.0);
        extent.setLeft(0.0);
        extent.setBottom(0.0);
        extent.setTop(0.0);

        final Gismapview gismapview = gisMapFactory.createGismapview();
        gismapview.setLayers(layers);
        gismapview.setExtent(extent);

        final Marshaller marshaller = JaxbUtilities.createMarshaller(jc);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        final StringWriter w = new StringWriter();
        marshaller.marshal(gismapview, w);
        w.close();

        final String string = w.toString();

        // als StorageInput zurckgeben
        final String basename = FilenameUtils.removeExtension(file.getName());
        final String gftName = basename + ".gmt"; //$NON-NLS-1$
        final IFile gftFile = file.getParent().getFile(new Path(gftName));
        final IPath fullPath = gftFile.getFullPath();

        return new StorageEditorInput(new StringStorage(string, fullPath));
    } catch (final JAXBException e) {
        throw new CoreException(StatusUtilities.statusFromThrowable(e));
    } catch (final IOException e) {
        throw new CoreException(StatusUtilities.statusFromThrowable(e));
    }
}

From source file:org.shredzone.cilla.service.notification.NotificationServiceImpl.java

/**
 * Send a {@link Notification} to a single {@link NotificationTarget}.
 * <p>/*  w w w . ja va  2 s. co  m*/
 * For the receiver's locale, the appropriate template is opened, it's placeholders
 * filled with the notification parameters, and the message sent to the target's
 * mail address.
 *
 * @param target
 *            {@link NotificationTarget} to send to
 * @param notification
 *            {@link Notification} to send
 */
private void sendToTarget(NotificationTarget target, Notification notification) throws CillaServiceException {
    try {
        Template template = freemarkerConfiguration.getTemplate(notification.getType() + ".ftl",
                target.getLocale());

        StringWriter out = new StringWriter();
        Environment env = template.createProcessingEnvironment(notification.getAttributes(), out, null);
        env.process();
        out.close();

        TemplateModel subjectTm = env.getVariable("subject");

        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setFrom(sender);
        msg.setTo(target.getMail());
        msg.setSubject(subjectTm != null ? subjectTm.toString() : "");
        msg.setText(out.toString());
        mailSender.send(msg);

    } catch (IOException | TemplateException ex) {
        log.error("Failed to process template ", ex);
        throw new CillaServiceException("Could not process template", ex);
    }
}

From source file:be.dnsbelgium.rdap.jackson.AbstractSerializerTest.java

@SuppressWarnings("unchecked")
public void serializeAndAssertEquals(String expected, S o, SerializerProvider sp) throws IOException {
    JsonFactory factory = new JsonFactory();
    T serializer = getSerializer();//ww  w .j  a va 2s .c om
    StringWriter sw = new StringWriter();
    JsonGenerator jgen = factory.createJsonGenerator(sw);
    serializer.serialize(o, jgen, sp); // unchecked
    jgen.flush();
    sw.flush();
    String result = sw.toString();
    sw.close();
    assertEquals(expected, result);
}

From source file:com.jaeksoft.searchlib.util.Timer.java

final public void setError(Exception exception) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    exception.printStackTrace(pw);/*from   w w  w  .ja  va 2 s .  c  om*/
    pw.close();
    try {
        sw.close();
    } catch (IOException e) {
        Logging.warn(e.getMessage(), e);
    }
    this.error = sw.toString();
}

From source file:org.pivot4j.state.StateSavingIT.java

@Test
public void testSaveModelSettings() throws ConfigurationException, IOException {
    PivotModel model = getPivotModel();//from   w w  w  .  j a v  a 2s . c om
    model.setMdx(getTestQuery());
    model.initialize();

    model.setSorting(true);
    model.setTopBottomCount(3);
    model.setSortCriteria(SortCriteria.BOTTOMCOUNT);

    CellSet cellSet = model.getCellSet();
    CellSetAxis axis = cellSet.getAxes().get(Axis.COLUMNS.axisOrdinal());

    model.sort(axis, axis.getPositions().get(0));

    String mdx = model.getCurrentMdx();

    XMLConfiguration configuration = new XMLConfiguration();
    configuration.setDelimiterParsingDisabled(true);

    model.saveSettings(configuration);

    Logger logger = LoggerFactory.getLogger(getClass());
    if (logger.isDebugEnabled()) {
        StringWriter writer = new StringWriter();
        configuration.save(writer);
        writer.flush();
        writer.close();

        logger.debug("Loading report content :" + System.getProperty("line.separator"));
        logger.debug(writer.getBuffer().toString());
    }

    PivotModel newModel = new PivotModelImpl(getDataSource());
    newModel.restoreSettings(configuration);

    newModel.getCellSet();

    String newMdx = newModel.getCurrentMdx();
    if (newMdx != null) {
        // Currently the parser treats every number as double value.
        // It's inevitable now and does not impact the result.
        newMdx = newMdx.replaceAll("3\\.0", "3");
    }

    assertThat("MDX has been changed after the state restoration", newMdx, is(equalTo(mdx)));
    assertThat("RenderProperty 'sorting' has been changed after the state restoration", newModel.isSorting(),
            is(true));
    assertThat("RenderProperty 'topBottomCount' has been changed after the state restoration",
            newModel.getTopBottomCount(), is(equalTo(3)));
    assertThat("RenderProperty 'sortMode' has been changed after the state restoration",
            newModel.getSortCriteria(), is(equalTo(SortCriteria.BOTTOMCOUNT)));
}

From source file:org.wso2.carbon.connector.rm.utils.ReliableMessageUtil.java

/**
 * Convert SOAPEnvelope to inputStream//from  w w w. j a  v  a2s  . co m
 *
 * @param soapEnvelope soapEnvelop.
 * @throws ConnectException
 * @retuen InputStream converted inputStream.
 */
public static InputStream getSOAPEnvelopAsStreamSource(SOAPEnvelope soapEnvelope) throws ConnectException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder;
    StringWriter stringWriter = null;

    try {

        docBuilder = documentBuilderFactory.newDocumentBuilder();
        stringWriter = new StringWriter();
        String soapEnvelop = "";
        if (soapEnvelope != null && soapEnvelope.getBody() != null) {
            soapEnvelop = soapEnvelope.getBody().toString();
        }
        Document doc = docBuilder.parse(new InputSource(new StringReader(soapEnvelop)));
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer trans = transformerFactory.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        StreamResult result = new StreamResult(stringWriter);
        DOMSource source = new DOMSource(doc);
        trans.transform(source, result);
    } catch (Exception e) {
        String message = "Failed to parse SOAPEnvelop request in to StreamSource";
        throwException(message, e);
    } finally {
        try {
            if (stringWriter != null) {
                stringWriter.close();
            }
        } catch (IOException e) {
            log.warn("Failed to close String writer:" + e.getMessage());
        }
    }
    return new ByteArrayInputStream(stringWriter.toString().getBytes());
}