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:edu.wisc.my.portlets.dmp.web.CachingXsltView.java

@SuppressWarnings("unchecked")
@Override//from  w  w  w  .  j a  v a2s.  c  o m
protected void doTransform(Map model, Source source, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    final Map parameters = getParameters(model, request);
    final Serializable cacheKey = this.getCacheKey(model, source, parameters);

    String cachedData;
    synchronized (this.xsltResultCache) {
        cachedData = this.xsltResultCache.get(cacheKey);
        if (cachedData == null) {
            final StringWriter writer = new StringWriter();

            final String encoding = response.getCharacterEncoding();
            this.doTransform(source, parameters, new StreamResult(writer), encoding);

            cachedData = writer.getBuffer().toString();
            this.xsltResultCache.put(cacheKey, cachedData);
        }
    }

    if (useWriter()) {
        final PrintWriter writer = response.getWriter();
        writer.write(cachedData);
        writer.flush();
    } else {
        final OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(cachedData.getBytes());
        outputStream.flush();
    }
}

From source file:org.apache.storm.sql.runtime.serde.csv.CsvSerializer.java

@Override
public ByteBuffer write(List<Object> data, ByteBuffer buffer) {
    try {/*from   ww w  .j  av a2 s .c o  m*/
        StringWriter writer = new StringWriter();
        CSVPrinter printer = new CSVPrinter(writer, CSVFormat.RFC4180);
        for (Object o : data) {
            printer.print(o);
        }
        //since using StringWriter, we do not need to close it.
        return ByteBuffer.wrap(writer.getBuffer().toString().getBytes(StandardCharsets.UTF_8));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:bigbluej.Client.java

private String toXml(Config config) {
    StringWriter stringWriter = new StringWriter();
    JAXB.marshal(config, stringWriter);
    return stringWriter.getBuffer().toString();
}

From source file:jp.xet.uncommons.wicket.utils.ErrorReportRequestCycleListener.java

String getStackTrace(Throwable throwable) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw, true);
    throwable.printStackTrace(pw);/*from ww  w .  j a v a  2s. c  o  m*/
    return sw.getBuffer().toString();
}

From source file:io.sledge.core.impl.installer.SledgePackageConfigurer.java

@Override
public Properties mergeProperties(String envFileContent, Properties propsForMerge) {
    Properties mergedProps = new Properties();
    try {//from  w  ww . j a v  a2 s. co m

        // Support internal property references for application package provided properties
        Properties origProps = new Properties();
        origProps.load(new StringReader(envFileContent));
        String configuredEnvironmentFileContent = StrSubstitutor.replace(envFileContent, origProps);

        mergedProps.load(new StringReader(configuredEnvironmentFileContent));

        // Support internal property references for overwrite properties
        StringWriter propsForMergeWriter = new StringWriter();
        propsForMerge.store(propsForMergeWriter, "");
        String propsForMergeAsString = propsForMergeWriter.getBuffer().toString();
        String configuredPropsForMerge = StrSubstitutor.replace(propsForMergeAsString, propsForMerge);
        Properties reconfiguredPropsForMerge = new Properties();
        reconfiguredPropsForMerge.load(new StringReader(configuredPropsForMerge));

        mergedProps.putAll(reconfiguredPropsForMerge);

    } catch (IOException e) {
        throw new InstallationException("Could not load environment properties.", e);
    }

    return mergedProps;
}

From source file:com.netflix.hystrix.contrib.sample.stream.HystrixUtilizationJsonStream.java

protected static String convertToJson(HystrixUtilization utilization) throws IOException {
    StringWriter jsonString = new StringWriter();
    JsonGenerator json = jsonFactory.createGenerator(jsonString);

    json.writeStartObject();/*from   ww  w .j  a v  a 2  s  . c  om*/
    json.writeStringField("type", "HystrixUtilization");
    json.writeObjectFieldStart("commands");
    for (Map.Entry<HystrixCommandKey, HystrixCommandUtilization> entry : utilization.getCommandUtilizationMap()
            .entrySet()) {
        final HystrixCommandKey key = entry.getKey();
        final HystrixCommandUtilization commandUtilization = entry.getValue();
        writeCommandUtilizationJson(json, key, commandUtilization);

    }
    json.writeEndObject();

    json.writeObjectFieldStart("threadpools");
    for (Map.Entry<HystrixThreadPoolKey, HystrixThreadPoolUtilization> entry : utilization
            .getThreadPoolUtilizationMap().entrySet()) {
        final HystrixThreadPoolKey threadPoolKey = entry.getKey();
        final HystrixThreadPoolUtilization threadPoolUtilization = entry.getValue();
        writeThreadPoolUtilizationJson(json, threadPoolKey, threadPoolUtilization);
    }
    json.writeEndObject();
    json.writeEndObject();
    json.close();

    return jsonString.getBuffer().toString();
}

From source file:dk.dbc.rawrepo.oai.ResumptionTokenTest.java

@Test
public void testXmlExpiration() throws Exception {
    ObjectNode jsonOriginal = (ObjectNode) new ObjectMapper().readTree("{\"foo\":\"bar\"}");

    long now = Instant.now().getEpochSecond();
    ResumptionTokenType token = ResumptionToken.toToken(jsonOriginal, 0);

    OAIPMH oaipmh = OBJECT_FACTORY.createOAIPMH();
    ListRecordsType getRecord = OBJECT_FACTORY.createListRecordsType();
    oaipmh.setListRecords(getRecord);/*from   w w  w  .  j ava2s  . c  om*/
    getRecord.setResumptionToken(token);
    JAXBContext context = JAXBContext.newInstance(OAIPMH.class);
    StringWriter writer = new StringWriter();
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(oaipmh, writer);
    String xml = writer.getBuffer().toString();
    System.out.println("XML is:\n" + xml);
    int start = xml.indexOf("expirationDate=\"") + "expirationDate=\"".length();
    int end = xml.indexOf("\"", start);
    String timestamp = xml.substring(start, end);
    System.out.println("timestamp = " + timestamp);

    assertTrue("Timestamp should be in ISO_INSTANT ending with Z", timestamp.endsWith("Z"));
    TemporalAccessor parse = DateTimeFormatter.ISO_INSTANT.withZone(ZoneId.systemDefault()).parse(timestamp);
    long epochSecond = Instant.from(parse).getEpochSecond();
    long diff = Math.abs(now - epochSecond);
    System.out.println("diff = " + diff);
    assertTrue("Difference between expirationdate and now should be 10 sec or less", diff <= 10);
}

From source file:gov.nih.nci.cdmsconnector.test.EnrollPatientTest.java

public void testEnrollPatientAPI() throws IOException, Exception {
    RegisterSubjectRequest request = getPopulatedEnrollPatientRequest();

    String beansFilePath = System.getProperty("catalina.home") + "/conf/c3d/applicationContext.xml";
    ApplicationContext ctx = new FileSystemXmlApplicationContext(beansFilePath);

    ClinicalConnectorImpl impl = (ClinicalConnectorImpl) ctx.getBean("c3DGridService");

    RegisterSubjectResponse response = impl.registerSubject(request);

    StringWriter writer = new StringWriter();
    Utils.serializeObject(response, new QName("EnrollPatientResponse"), writer);

    responseStr = writer.getBuffer().toString();
    log.debug(responseStr);//  w w  w  .j  av a2  s. co m

}

From source file:org.hexlogic.model.DockerNodeManager.java

private boolean dockerIsReachable(String hostName, int hostPortNumber, String dockerApiVersion) {
    DockerClient dockerClient = null;/*from  w  w  w.j a  va2 s  . c  o m*/
    try {
        // Fallback to default port if none was provided!
        if (!(hostPortNumber > 0) || !(hostPortNumber < 65535)) {
            hostPortNumber = DockerNode.defaultPort;
        }

        // Fallback to default API if none was provided!
        if (dockerApiVersion == null || dockerApiVersion.isEmpty()) {
            dockerApiVersion = DockerNode.defaultApi;
        }

        DockerClientConfig config = DockerClientConfig.createDefaultConfigBuilder()
                .withVersion(dockerApiVersion).withUri("http://" + hostName + ":" + hostPortNumber)
                .withReadTimeout(10000) // 10 seconds timeout
                .build();
        dockerClient = DockerClientBuilder.getInstance(config)
                .withServiceLoaderClassLoader(CooptoPluginAdaptor.class.getClassLoader()).build();
    } catch (Exception e) {
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);
        log.error("Error: " + sw.getBuffer().toString());
        return false;
    }

    try {
        dockerClient.pingCmd().exec();
        return true;
    } catch (Exception e) {
        log.error("Error while adding Docker node - host was unreachable.");
        return false;
    }
}

From source file:bigbluej.Client.java

private String toXml(ModulesCommand modulesCommand) {
    Modules modules = new Modules();
    modules.setModules(new ArrayList<Module>());
    for (ModuleCommand moduleCommand : modulesCommand.getModules()) {
        Module module = new Module();
        module.setName(moduleCommand.getName());
        module.setDocuments(new ArrayList<Document>());
        for (DocumentCommand documentCommand : moduleCommand.getDocuments()) {
            Document document = new Document();
            document.setUrl(documentCommand.getUrl());
            if (StringUtils.isNotBlank(documentCommand.getName())) {
                document.setName(documentCommand.getName());
                document.setValue(Base64.encodeBase64String(documentCommand.getContent()));
                System.out.println("base64 value> " + document.getValue());
            }/*ww  w.j  av a  2s .  c  om*/
            module.getDocuments().add(document);
        }
        modules.getModules().add(module);
    }
    StringWriter stringWriter = new StringWriter();
    JAXB.marshal(modules, stringWriter);
    return stringWriter.getBuffer().toString();
}