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.scripps.fl.hibernate.StringListStringType.java

public String getStringFromList(List<String> ids) {
    if (null == ids)
        return null;
    StringWriter sw = new StringWriter();
    try {/*from  ww  w  .ja  v a2s.  c o  m*/
        CsvWriter writer = new CsvWriter(sw, ',');
        for (String value : ids)
            writer.write(value);
        writer.flush();
        writer.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return sw.getBuffer().toString();
}

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

public void testEnrollPatientService() throws Exception {
    ClinicalConnectorClient client = new ClinicalConnectorClient(url, getCredentials());

    RegisterSubjectRequest request = getPopulatedEnrollPatientRequest();

    RegisterSubjectResponse response = client.registerSubject(request);

    StringWriter writer = new StringWriter();

    /*Utils.serializeObject(response, new QName("EnrollPatientResponse"),
    writer);*//*from   ww w  . java2  s  . c om*/
    responseStr = writer.getBuffer().toString();
    log.debug(responseStr);

}

From source file:dk.defxws.fedoragsearch.server.GTransformer.java

public StringBuffer transform(String xsltName, Source sourceStream, URIResolver uriResolver,
        HashMap<String, String> params, boolean checkInHome) throws Exception {
    logger.fine("xsltName=" + xsltName);
    Transformer transformer = getTransformer(xsltName, uriResolver, checkInHome);
    //logger.info(params);
    Iterator it = params.keySet().iterator();
    String key = "";
    String value = "";
    while (it.hasNext()) {
        key = (String) it.next();
        value = params.get(key);//from   w w w  .j  a va 2 s  .co m
        if (value == null) {
            value = "";
        }
        transformer.setParameter(key, value);

    }
    transformer.setParameter("DATETIME", new Date());
    StreamResult destStream = new StreamResult(new StringWriter());
    try {
        transformer.transform(sourceStream, destStream);
    } catch (TransformerException e) {
        logger.log(Level.SEVERE, "transform " + xsltName + ":\n", e);
        throw new Exception("transform " + xsltName + ":\n", e);
    }
    StringWriter sw = (StringWriter) destStream.getWriter();
    //      if (logger.isDebugEnabled())
    //      logger.debug("sw="+sw.getBuffer().toString());
    return sw.getBuffer();
}

From source file:org.apache.streams.gnip.powertrack.ActivityXMLActivitySerializer.java

private String setContentIfEmpty(String xml) throws Exception {
    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(xml));
    Document doc = docBuilder.parse(is);
    doc.getDocumentElement().normalize();
    Element base = (Element) doc.getElementsByTagName("entry").item(0);
    NodeList nodeList = base.getChildNodes();
    //        for(int i=0; i < nodeList.getLength(); ++i) {
    //            System.out.println(nodeList.item(i).getNodeName());
    //        }/*from   ww w  .j  a v  a  2s . c om*/
    Element obj = (Element) base.getElementsByTagName("activity:object").item(0);
    Element content = (Element) obj.getElementsByTagName("content").item(0);
    //        System.out.println("Number of child nodes : "+content.getChildNodes().getLength());
    //        System.out.println("Text content before : "+content.getTextContent());
    if (content.getTextContent() == null || content.getTextContent().equals("")) {
        content.setTextContent(" ");
    }
    //        System.out.println("Number of child nodes after : "+content.getChildNodes().getLength());
    //        System.out.println("Text content after : "+content.getTextContent());
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    String output = writer.getBuffer().toString().replaceAll("\n|\r", "");
    //        System.out.println(output);
    //        System.out.println(output);
    //        System.out.println(content);
    return output;
}

From source file:de.iai.ilcd.services.PostResourceHelper.java

public Response importByFileUpload(DataSetType type, InputStream fileInputStream, RootDataStock rds) {

    String tempFileName = ConfigurationService.INSTANCE.getUniqueUploadFileName("IMPORT", "xml");

    try { // we have to copy the uploaded file to a temporary space first; maybe later we find a better solution
        FileOutputStream fos = new FileOutputStream(tempFileName);
        IOUtils.copy(fileInputStream, fos);
        fileInputStream.close();//from  w  w  w  . j av  a  2 s.  co  m
        fos.close();
    } catch (IOException e) {
        logger.error("Cannot save an uploaded file to temporary storage");
        logger.error("exception is: ", e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity("Cannot save uploaded file to temporary storage").build();
    }

    DataSetImporter importer = new DataSetImporter();
    StringWriter writer = new StringWriter();
    PrintWriter out = new PrintWriter(writer);

    try {
        if (importer.importFile(type, tempFileName, out, rds) == true) {
            logger.info("data set successfully imported.");
            logger.info("{}", writer.getBuffer());
            out.println("data set successfully imported.");
            out.flush();
            return Response.ok(writer.getBuffer().toString(), MediaType.TEXT_PLAIN).build();
        } else {
            logger.error("Cannot import data set");
            logger.error("output is: {}", writer.getBuffer());
            return Response.status(Response.Status.NOT_ACCEPTABLE).type(MediaType.TEXT_PLAIN)
                    .entity(writer.getBuffer().toString()).build();
        }
    } catch (Exception e) {
        logger.error("cannot import data set");
        logger.error("exception is: ", e);
        return Response.status(Response.Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN)
                .entity(writer.getBuffer().toString()).build();
    }
}

From source file:com.wordnik.swagger.testframework.JavaTestCaseExecutor.java

private void executeTestCase(String resourceName, String servicePackageName, String suggestedName,
        Map<String, String> queryAndPathParameters, String postData) {

    String className = namingPolicyProvider.getServiceName(resourceName);
    String methodName = suggestedName;
    //3/*from   w w w.ja  v a 2 s . c o m*/
    try {
        Class apiClass = Class.forName(servicePackageName + "." + className);
        Method[] methods = apiClass.getMethods();
        Method methodToExecute = null;
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                methodToExecute = method;
                break;
            }
        }

        if (methodToExecute != null) {
            //4
            Object[] arguments = populateArgumentsForTestCaseExecution(methodToExecute, queryAndPathParameters,
                    postData, className, resourceName);
            Object output = null;
            if (arguments != null && arguments.length > 0) {
                //5
                output = methodToExecute.invoke(null, arguments);
            } else {
                //5
                output = methodToExecute.invoke(null);
            }
            //6
            System.out.println("SUCCESS");
            System.out.println(APITestRunner.convertObjectToJSONString(output));

        }
    } catch (APIException e) {
        StringWriter sWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(sWriter);
        e.printStackTrace(writer);
        System.out.println(sWriter.getBuffer().toString());
        System.out.println(e.getMessage());
        System.out.println("ERROR");
        try {
            System.out.println(APITestRunner.convertObjectToJSONString(e));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    } catch (Exception e) {
        StringWriter sWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(sWriter);
        e.printStackTrace(writer);
        System.out.println(sWriter.getBuffer().toString());
        e.printStackTrace();
        System.out.println("ERROR");
        try {
            APIException apiException = new APIException(APIExceptionCodes.SYSTEM_EXCEPTION, e.getMessage());
            System.out.println(APITestRunner.convertObjectToJSONString(apiException));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:mx.redhat.jbpm.CustomType.FileCustomType.java

public String renderField(String fieldName, String path, String namespace, boolean showInput) {
    /*/*from w  w w . j a  va2 s.co  m*/
     * We are using a .ftl template to generate the HTML to show on screen, as it is a sample you can use any other way to do that.
     * To see the template format look at input.ftl on the resources folder.
     */
    String str = null;
    try {
        File file = null;
        if (!StringUtils.isEmpty(path)) {
            file = fileStorageService.getFile(path);
        }

        Map<String, Object> context = new HashMap<String, Object>();

        // if there is a file in the specified path, the input will show a link to download it.
        context.put("inputId", namespace + "_file_" + fieldName);
        if (file != null && file.exists()) {
            /*
             * Building the parameter map for the download link.
             * We are encoding the file path in order to make a download link cleaner
             */
            Map params = new HashMap();
            params.put("content", Base64.encodeBase64String(path.getBytes()));

            /*
             * Building the download link:
             * For this sample we created a FileDownloadHandler that will execute the download action. We used the @Named("fdch") annotation to identify it.
             * To generate the link we are using the URLMarkupGenerator from jbpm-form-modeler-request-dispatcher module. It generates a markup to the FileDownloadHandler
             * using the parameters:
             * "fdch"       -> Identifier of the Bean that will execute the action (you can also use the Canonical Name of the Bean "org.jbpm.formModeler.core.fieldTypes.file.FileDownloadHandler")
             * "download"   -> Action to execute
             * params       -> A map containing the parameters that the action requires. In that case only the file path in Base64.
             */
            String downloadLink = urlMarkupGenerator.getMarkup("fdch", "download", params);

            context.put("showLink", Boolean.TRUE);
            context.put("downloadLink", downloadLink);
            context.put("fileName", file.getName());
            context.put("fileSize", getFileSize(file.length()));
            context.put("fileIcon", getFileIcon(file));
            context.put("dropIcon", dropIcon);
        } else {
            context.put("showLink", Boolean.FALSE);
        }
        // If the field is readonly or we are just showing the field value we will hide the input file.
        context.put("showInput", showInput);

        InputStream src = this.getClass().getResourceAsStream("/input.ftl");
        freemarker.template.Configuration cfg = new freemarker.template.Configuration();
        BeansWrapper defaultInstance = new BeansWrapper();
        defaultInstance.setSimpleMapWrapper(true);
        cfg.setObjectWrapper(defaultInstance);
        cfg.setTemplateUpdateDelay(0);
        Template temp = new Template(fieldName, new InputStreamReader(src), cfg);
        StringWriter out = new StringWriter();
        temp.process(context, out);
        out.flush();
        str = out.getBuffer().toString();
    } catch (Exception e) {
        log.warn("Failed to process template for field '{}'", fieldName, e);
    }
    return str;
}

From source file:com.jayway.jsonpath.internal.spi.json.JacksonJsonProvider.java

@Override
public String toJson(Object obj) {
    StringWriter writer = new StringWriter();
    try {/* w ww .j a va  2s.com*/
        JsonGenerator generator = objectMapper.getFactory().createGenerator(writer);
        objectMapper.writeValue(generator, obj);
        writer.flush();
        writer.close();
        generator.close();
        return writer.getBuffer().toString();
    } catch (IOException e) {
        throw new InvalidJsonException();
    }
}

From source file:com.seyren.core.service.notification.EmailNotificationService.java

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts) {

    try {//w  ww . j  a  v  a  2s . com
        VelocityContext context = createVelocityContext(check, subscription, alerts);

        StringWriter w = new StringWriter();
        Velocity.evaluate(context, w, "EmailNotificationService", getTemplateAsString());

        Email email = new Email().withTo(subscription.getTarget()).withFrom(seyrenConfig.getSmtpFrom())
                .withSubject(createSubject(check)).withMessage(w.getBuffer().toString());

        mailSender.send(createMimeMessage(email));

    } catch (Exception e) {
        throw new NotificationFailedException("Failed to send notification to " + subscription.getTarget()
                + " from " + seyrenConfig.getSmtpFrom(), e);
    }
}

From source file:io.debezium.document.JacksonWriter.java

@Override
public String write(Array array) throws IOException {
    StringWriter writer = new StringWriter();
    try (JsonGenerator jsonGenerator = factory.createGenerator(writer)) {
        configure(jsonGenerator);/*from   w  ww  .j a v  a 2 s.com*/
        writeArray(array, jsonGenerator);
    }
    return writer.getBuffer().toString();
}