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:org.kalypso.ui.editorLauncher.FeatureTemplateLauncher.java

/**
 * @throws CoreException//from www.ja  v  a  2  s. co m
 * @see org.kalypso.ui.editorLauncher.IDefaultTemplateLauncher#createInput(org.eclipse.core.resources.IFile)
 */
@Override
public IEditorInput createInput(final IFile file) throws CoreException {
    try {
        // ein default template erzeugen
        final ObjectFactory factory = new ObjectFactory();
        final JAXBContext jc = JaxbUtilities.createQuiet(ObjectFactory.class);
        final Layer layer = factory.createFeaturetemplateLayer();
        LayerTypeUtilities.initLayerType(layer, file, null);

        final Featuretemplate featuretemplate = factory.createFeaturetemplate();
        featuretemplate.setLayer(layer);

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

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

        final String templateXml = w.toString();

        // als StorageInput zurckgeben
        final String basename = FilenameUtils.removeExtension(file.getName());
        final String gftName = basename + EXT_GFT;
        final IFile gftFile = file.getParent().getFile(new Path(gftName));
        final IPath fullPath = gftFile.getFullPath();

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

From source file:com.amalto.workbench.utils.XmlUtil.java

public static String formatXmlSource(String xmlSource) {

    SAXReader reader = new SAXReader();
    StringReader stringReader = new StringReader(xmlSource);
    StringWriter writer = null;
    XMLWriter xmlwriter = null;/*from   w  ww.j  av  a2  s .  c  o  m*/
    String result = xmlSource;

    try {
        Document document = reader.read(stringReader);
        writer = new StringWriter();
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");//$NON-NLS-1$
        format.setIndentSize(4);
        format.setSuppressDeclaration(true);
        xmlwriter = new XMLWriter(writer, format);
        xmlwriter.write(document);
        result = writer.toString();
    } catch (Exception e) {

    } finally {

        try {
            if (stringReader != null)
                stringReader.close();

            if (xmlwriter != null)
                xmlwriter.close();

            if (writer != null)
                writer.close();

        } catch (Exception e) {

        }

    }
    return result;

}

From source file:org.geowebcache.rest.seed.GWCSeedingRestlet.java

/**
 * Deserializing a json string is more complicated.
 * //from   ww  w .java 2s.c o  m
 * XStream does not natively support it. Rather, it uses a JettisonMappedXmlDriver to convert to
 * intermediate xml and then deserializes that into the desired object. At this time, there is a
 * known issue with the Jettison driver involving elements that come after an array in the json
 * string.
 * 
 * http://jira.codehaus.org/browse/JETTISON-48
 * 
 * The code below is a hack: it treats the json string as text, then converts it to the
 * intermediate xml and then deserializes that into the SeedRequest object.
 */
private String convertJson(String entityText) throws IOException {
    HierarchicalStreamDriver driver = new JettisonMappedXmlDriver();
    StringReader reader = new StringReader(entityText);
    HierarchicalStreamReader hsr = driver.createReader(reader);
    StringWriter writer = new StringWriter();
    new HierarchicalStreamCopier().copy(hsr, new PrettyPrintWriter(writer));
    writer.close();
    return writer.toString();
}

From source file:com.glaf.template.renderer.freemarker.FreemarkerRenderer.java

public void render(Map<String, Object> model, Writer out) {
    try {/*from w  ww . j  a  v a 2s  . c o  m*/
        if (parseException != null) {
            Map<String, Object> context = new java.util.HashMap<String, Object>();
            context.put("exception", parseException);
            context.put("exceptionSource", renderTemplate.getTemplateId());
            t.process(context, out);
            return;
        }
        model.put("currentDate", new java.util.Date());
        log.debug(model);
        StringWriter writer = new StringWriter();
        long startTime = System.currentTimeMillis();
        t.process(model, writer);
        writer.flush();
        writer.close();
        out.write(writer.toString());
        long endTime = System.currentTimeMillis();
        long renderTime = (endTime - startTime);
        log.debug("Rendered [" + renderTemplate.getTemplateId() + "] in " + renderTime + " milliseconds");
        // log.debug(out.toString());
    } catch (Exception ex) {
        throw new RuntimeException("Error during rendering", ex);
    }
}

From source file:org.apache.hadoop.hbase.util.JSONBean.java

/**
 * Dump out a subset of regionserver mbeans only, not all of them, as json on System.out.
 * @throws MalformedObjectNameException// w ww  .j  a va2  s .  c o m
 * @throws IOException
 */
public static String dumpRegionServerMetrics() throws MalformedObjectNameException, IOException {
    StringWriter sw = new StringWriter(1024 * 100); // Guess this size
    try (PrintWriter writer = new PrintWriter(sw)) {
        JSONBean dumper = new JSONBean();
        try (JSONBean.Writer jsonBeanWriter = dumper.open(writer)) {
            MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
            jsonBeanWriter.write(mbeanServer, new ObjectName("java.lang:type=Memory"), null, false);
            jsonBeanWriter.write(mbeanServer, new ObjectName("Hadoop:service=HBase,name=RegionServer,sub=IPC"),
                    null, false);
            jsonBeanWriter.write(mbeanServer,
                    new ObjectName("Hadoop:service=HBase,name=RegionServer,sub=Replication"), null, false);
            jsonBeanWriter.write(mbeanServer,
                    new ObjectName("Hadoop:service=HBase,name=RegionServer,sub=Server"), null, false);
        }
    }
    sw.close();
    return sw.toString();
}

From source file:org.jcurl.core.xsio.XppMiniTest.java

public void testTrivial2() {
    final XStream xs = new XStream() {
        final String rootElem = "wrap";

        final String rootNS = "mynamespace";

        private HierarchicalStreamReader checkRoot(HierarchicalStreamReader arg0) {
            if (rootElem.equals(arg0.getNodeName()) && rootNS.equals(arg0.getAttribute("xmlns"))) {
                log.debug("Found korrekt root!");
                arg0.moveDown();/*from   w  w  w  .j a  va2s .c o  m*/
            }
            return arg0;
        }

        @Override
        public String toXML(Object arg0) {
            try {
                StringWriter w = new StringWriter();
                toXML(arg0, w);
                w.close();
                return w.getBuffer().toString();
            } catch (IOException e) {
                throw new RuntimeException("Unhandled", e);
            }
        }

        @Override
        public void toXML(Object arg0, OutputStream arg1) {
            throw new NotImplementedYetException();
        }

        @Override
        public void toXML(Object arg0, Writer arg1) {
            try {
                arg1.write("<?xml version='1.0'?>\n<");
                arg1.write(rootElem);
                arg1.write(" xmlns='");
                arg1.write(rootNS);
                arg1.write("'>\n");
                super.toXML(arg0, arg1);
                arg1.write("<");
                arg1.write(rootElem);
                arg1.write(">");
            } catch (IOException e) {
                throw new RuntimeException("Unhandled", e);
            }
        }

        @Override
        public Object unmarshal(HierarchicalStreamReader arg0) {
            return super.unmarshal(checkRoot(arg0));
        }

        @Override
        public Object unmarshal(HierarchicalStreamReader arg0, Object arg1) {
            return super.unmarshal(checkRoot(arg0), arg1);
        }

        @Override
        public Object unmarshal(HierarchicalStreamReader arg0, Object arg1, DataHolder arg2) {
            return super.unmarshal(checkRoot(arg0), arg1, arg2);
        }
    };
    assertEquals("Hello, world", xs
            .fromXML("<?xml version='1.0'?>\n<wrap xmlns='mynamespace'><string>Hello, world</string></wrap>"));

    assertEquals(
            "<?xml version='1.0'?>\n" + "<wrap xmlns='mynamespace'>\n" + "<string>Hallo, Welt!</string><wrap>",
            xs.toXML("Hallo, Welt!"));

    assertEquals("Hallo, Welt!!", xs.fromXML(xs.toXML("Hallo, Welt!!")));
}

From source file:org.unitime.timetable.util.BlobRoomAvailabilityService.java

protected void sendRequest(Document request) throws IOException {
    try {/*from   w w w.  j  a v a2  s. c  o  m*/
        StringWriter writer = new StringWriter();
        (new XMLWriter(writer, OutputFormat.createPrettyPrint())).write(request);
        writer.flush();
        writer.close();
        SessionImplementor session = (SessionImplementor) new _RootDAO().getSession();
        Connection connection = session.getJdbcConnectionAccess().obtainConnection();
        try {
            CallableStatement call = connection.prepareCall(iRequestSql);
            call.setString(1, writer.getBuffer().toString());
            call.execute();
            call.close();
        } finally {
            session.getJdbcConnectionAccess().releaseConnection(connection);
        }
    } catch (Exception e) {
        sLog.error("Unable to send request: " + e.getMessage(), e);
    } finally {
        _RootDAO.closeCurrentThreadSessions();
    }
}

From source file:architecture.common.license.io.LicenseReader.java

public String prettyPrintLicense(String decryptedLicenseKey) throws LicenseException {
    try {//from   w w w  .  j a v a2 s.co m
        StringReader reader = new StringReader(decryptedLicenseKey);
        org.dom4j.Document doc = (new SAXReader()).read(reader);
        reader.close();
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        outputFormat.setNewlines(true);
        outputFormat.setTrimText(false);
        StringWriter writer = new StringWriter();
        XMLWriter xmlWriter = new XMLWriter(writer, outputFormat);
        xmlWriter.write(doc);
        writer.close();
        return writer.toString();
    } catch (Exception e) {
        throw new LicenseException(e);
    }
}

From source file:org.hawkular.datamining.api.SerializationTest.java

private String serialize(Object object) throws IOException {
    StringWriter out = new StringWriter();

    JsonGenerator gen = mapper.getFactory().createGenerator(out);

    gen.writeObject(object);/*from   ww  w.  j a v a 2s  .  c  om*/

    gen.close();

    out.close();

    return out.toString();
}

From source file:org.nuxeo.ecm.platform.ui.web.component.seam.UICellExcel.java

/**
 * Helper method for rendering a component (usually on a facescontext with a caching reponsewriter)
 *
 * @param facesContext The faces context to render to
 * @param component The component to render
 * @return The textual representation of the component
 * @throws IOException If the JSF helper class can't render the component
 *//*from w ww.  j  av  a2  s .  c  om*/
public static String cmp2String(FacesContext facesContext, UIComponent component) throws IOException {
    ResponseWriter oldResponseWriter = facesContext.getResponseWriter();
    String contentType = oldResponseWriter != null ? oldResponseWriter.getContentType() : DEFAULT_CONTENT_TYPE;
    String characterEncoding = oldResponseWriter != null ? oldResponseWriter.getCharacterEncoding()
            : DEFAULT_CHARACTER_ENCODING;
    StringWriter cacheingWriter = new StringWriter();

    // XXX: create a response writer by hand, to control html escaping of
    // iso characters
    // take default values for these confs
    Boolean scriptHiding = Boolean.FALSE;
    Boolean scriptInAttributes = Boolean.TRUE;
    // force escaping to true
    WebConfiguration.DisableUnicodeEscaping escaping = WebConfiguration.DisableUnicodeEscaping.True;
    ResponseWriter newResponseWriter = new NXHtmlResponseWriter(cacheingWriter, contentType, characterEncoding,
            scriptHiding, scriptInAttributes, escaping);
    // ResponseWriter newResponseWriter = renderKit.createResponseWriter(
    // cacheingWriter, contentType, characterEncoding);

    facesContext.setResponseWriter(newResponseWriter);
    JSF.renderChild(facesContext, component);
    if (oldResponseWriter != null) {
        facesContext.setResponseWriter(oldResponseWriter);
    }
    cacheingWriter.flush();
    cacheingWriter.close();
    return cacheingWriter.toString();
}