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:org.posterita.core.AbstractChart.java

public String getImageMap(String imageMapName) throws OperationException {
    try {/*www . j av  a2  s .  c  om*/
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        ChartUtilities.writeImageMap(printWriter, imageMapName, renderingInfo, false);
        printWriter.flush();

        String imageMap = stringWriter.getBuffer().toString();
        return imageMap;
    } catch (IOException e) {
        throw new OperationException("Problem occured while writing imagemap", e);
    }
}

From source file:com.mnxfst.stream.pipeline.element.script.ScriptEvaluatorPipelineElementTest.java

/**
 * This is not a test case but more a kind of a sandbox for fiddling around with the script engine
 *///from  w ww.j a v  a 2s .c o  m
@Test
public void testEvaluateScriptWithReturn() throws Exception {

    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    StringWriter writer = new StringWriter();
    PrintWriter pw = new PrintWriter(writer, true);
    engine.getContext().setWriter(pw);

    engine.eval(new FileReader("/home/mnxfst/git/stream-analyzer/src/main/resources/spahql.js"));

    String script = "var result0 = '1';var result1 = '2';";
    engine.eval(script);
    StringBuffer sb = writer.getBuffer();
    System.out.println("StringBuffer contains: " + sb + " - " + engine.get("test"));
    System.out.println(engine.get("content"));

    for (int i = 0; i < Integer.MAX_VALUE; i++) {
        String content = (String) engine.get("result" + i);
        if (StringUtils.isBlank(content))
            break;
        System.out.println(content);
    }

    ObjectMapper mapper = new ObjectMapper();
    StreamEventMessage message = new StreamEventMessage();
    message.setIdentifier("test-id");
    message.setOrigin("test-origin");
    message.setTimestamp("2014-03-05");
    message.setEvent("10");
    //      message.addCustomAttribute("test-key-1", "3");
    //      message.addCustomAttribute("test-key-2", "value-1");
    //      message.addCustomAttribute("test-key-3", "19");
    //      message.addCustomAttribute("errors", (String)engine.get("test"));

    String json = mapper.writeValueAsString(message);
    System.out.println(json);
    StreamEventMessage msg = mapper.readValue(json, StreamEventMessage.class);
    System.out.println(message.getCustomAttributes().get("json"));

}

From source file:com.npower.cp.VelocityTemplateMerger.java

/**
 * @param templateID/*  w  w w . ja  v  a  2  s . c o m*/
 * @param templateContent
 * @param settings
 * @return
 * @throws OTAException
 */
private ProvisioningDoc merge(String templateID, String templateContent, Object settings) throws OTAException {
    if (StringUtils.isEmpty(templateID)) {
        templateID = "Unknown";
    }
    try {
        //Velocity velocity = new Velocity();
        Velocity.init();
        // Any values specified before init() time will replace the default values.
        //velocity.setProperty("resource.loader", "file");
        //velocity.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
        //velocity.setProperty("file.resource.loader.path", System.getProperty("java.io.tmpdir"));

        VelocityContext context = new VelocityContext();
        if (settings != null) {
            context.put("profile", settings);
        }

        StringWriter out = new StringWriter();
        Velocity.evaluate(context, out, "OTATemplate ID:" + templateID, new StringReader(templateContent));
        // Pretty format XML document
        try {
            XMLPrettyFormatter formatter = new XMLPrettyFormatter(out.getBuffer().toString());
            out = new StringWriter();
            out.write(formatter.format());
        } catch (DocumentException ex) {
            // Ignore this error
            log.error("Error in pretty cp xml message: " + ex.getMessage(), ex);
        }

        //String templateFile = this.outputTmpFile(this.getContent());
        //Template veloTemplate = velocity.getTemplate(templateFile, "UTF-8");
        //veloTemplate.merge(context, out);
        ProvisioningDoc doc = new ProvisioningDocImpl(out);
        log.info("Merged CP Template: " + doc.getContent());
        return doc;
    } catch (ResourceNotFoundException e) {
        throw new OTAException(e);
    } catch (ParseErrorException e) {
        throw new OTAException(e);
    } catch (Exception e) {
        throw new OTAException(e);
    }
}

From source file:com.alu.e3.prov.service.ApiJarBuilder.java

protected void doGenXML(List<JarEntryData> entries, Api api, Map<Object, Object> variablesMap)
        throws IOException, TemplateException {
    Template template = fmConfiguration.getTemplate(ROUTE_TEMPLATE_PATH);
    StringWriter buffer = new StringWriter();
    template.process(variablesMap, buffer);
    buffer.flush();/* w  w  w . jav a2s.  c o  m*/

    if (LOG.isDebugEnabled())
        LOG.debug(buffer.getBuffer().toString());

    addJarEntry(entries, buffer.getBuffer().toString().getBytes("UTF-8"), "META-INF/spring/route-context.xml");
}

From source file:com.chenchengzhi.windtalkers.server.WindMessageFactory.java

protected HttpResponse throwError(Issue issue) throws IOException {
    HttpResponse errorResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(issue.getStatusCode().getCode()));

    ObjectNode errorNode = issue.translate();
    StringWriter writer = new StringWriter();
    JsonGenerator generator = jsonFactory.createJsonGenerator(writer);
    generator.setPrettyPrinter(new DefaultPrettyPrinter());
    errorNode.serialize(generator, new DefaultSerializerProvider.Impl());
    generator.flush();//from  w  ww . ja  v a 2  s . c o m

    errorResponse.setContent(ChannelBuffers.copiedBuffer(writer.getBuffer(), Charsets.UTF_8));
    errorResponse.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/json");
    errorResponse.setHeader(HttpHeaders.Names.CONTENT_LENGTH, errorResponse.getContent().readableBytes());
    return errorResponse;
}

From source file:com.alu.e3.prov.service.ApiJarBuilder.java

protected void doGenManifest(List<JarEntryData> entries, Api api, Map<Object, Object> variablesMap)
        throws IOException, TemplateException {
    Template template = fmConfiguration.getTemplate(MANIFEST_TEMPLATE_PATH);
    StringWriter buffer = new StringWriter();
    template.process(variablesMap, buffer);
    buffer.flush();/*from   w w  w. j  a  v  a 2 s  .c om*/

    if (LOG.isDebugEnabled())
        LOG.debug(buffer.getBuffer().toString());

    addJarEntry(entries, buffer.getBuffer().toString().getBytes("UTF-8"), "META-INF/MANIFEST.MF");

}

From source file:de.fischer.thotti.core.distbuilder.DistributionBuilder.java

protected void generateRunSkript(ArchiveOutputStream os)
        throws IOException, TemplateException, AWSRessourceNotFoundException, AWSIllegalConfigurationException {
    // @todo Improve Exception handling

    AWSAccessCredentials remoteCredentials = getRemoteUsersCredentials();

    Configuration cfg = new Configuration();
    cfg.setClassForTemplateLoading(this.getClass(), "/freemarker/distribution");
    cfg.setLocalizedLookup(false);//from  www  .j  a  v a2s .c o m
    cfg.setObjectWrapper(new DefaultObjectWrapper());

    Map varMap = new HashMap();
    varMap.put("var_classpath", cpBuilder.toString());
    varMap.put("var_ak", remoteCredentials.getAccessKeyId());
    varMap.put("var_sk", remoteCredentials.getSecretKey());
    varMap.put("var_resultfile", NDRunner.THOTTI_RESULT_FILE);

    Template temp = null;
    temp = cfg.getTemplate("run.sh.ftl");
    StringWriter out = new StringWriter();
    temp.process(varMap, out);
    out.flush();

    String content = out.getBuffer().toString().replace("\r\n", "\n");

    String target = BASE_DIRECTORY + "/" + BIN_DIRECTORY + "/ndrunner";
    os.putArchiveEntry(new ZipArchiveEntry(target));
    IOUtils.copy(new ByteArrayInputStream(content.getBytes()), os);
    os.closeArchiveEntry();
}

From source file:org.camunda.spin.impl.json.jackson.query.JsonPathJacksonProvider.java

public String toJson(Object obj) {
    StringWriter writer = new StringWriter();
    try {/*from ww  w. j a  v  a2s.  co  m*/
        JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(writer);
        objectMapper.writeValue(jsonGenerator, obj);
        writer.close();
        return writer.getBuffer().toString();
    } catch (IOException e) {
        throw new InvalidJsonException();
    }
}

From source file:com.jaxio.celerio.util.IOUtil.java

/**
 * Write to a string the bytes read from an input stream.
 *
 * @param charset the charset used to read the input stream
 * @return the inputstream as a string/*from   w  w  w.  j a  v a2  s . co m*/
 */
public String inputStreamToString(InputStream is, String charset) throws IOException {
    InputStreamReader isr = null;
    if (null == charset) {
        isr = new InputStreamReader(is);
    } else {
        isr = new InputStreamReader(is, charset);
    }
    StringWriter sw = new StringWriter();
    int c = -1;
    while ((c = isr.read()) != -1) {
        sw.write(c);
    }
    isr.close();
    return sw.getBuffer().toString();
}

From source file:com.enonic.cms.server.service.admin.mvc.controller.SiteDebugInfoController.java

/**
 * Read external javascript file.//from  w w w. j a  v a 2 s.  com
 */
private String readStaticFile(Resource path) throws Exception {
    StringWriter out = new StringWriter();
    InputStreamReader in = new InputStreamReader(path.getInputStream());
    FileCopyUtils.copy(in, out);
    return out.getBuffer().toString();
}