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:com.netflix.hystrix.contrib.sample.stream.HystrixConfigurationJsonStream.java

public static String convertToString(HystrixConfiguration config) throws IOException {
    StringWriter jsonString = new StringWriter();
    JsonGenerator json = jsonFactory.createGenerator(jsonString);

    json.writeStartObject();/*from  w w  w .j a v  a 2s  .  c  o m*/
    json.writeStringField("type", "HystrixConfig");
    json.writeObjectFieldStart("commands");
    for (Map.Entry<HystrixCommandKey, HystrixCommandConfiguration> entry : config.getCommandConfig()
            .entrySet()) {
        final HystrixCommandKey key = entry.getKey();
        final HystrixCommandConfiguration commandConfig = entry.getValue();
        writeCommandConfigJson(json, key, commandConfig);

    }
    json.writeEndObject();

    json.writeObjectFieldStart("threadpools");
    for (Map.Entry<HystrixThreadPoolKey, HystrixThreadPoolConfiguration> entry : config.getThreadPoolConfig()
            .entrySet()) {
        final HystrixThreadPoolKey threadPoolKey = entry.getKey();
        final HystrixThreadPoolConfiguration threadPoolConfig = entry.getValue();
        writeThreadPoolConfigJson(json, threadPoolKey, threadPoolConfig);
    }
    json.writeEndObject();

    json.writeObjectFieldStart("collapsers");
    for (Map.Entry<HystrixCollapserKey, HystrixCollapserConfiguration> entry : config.getCollapserConfig()
            .entrySet()) {
        final HystrixCollapserKey collapserKey = entry.getKey();
        final HystrixCollapserConfiguration collapserConfig = entry.getValue();
        writeCollapserConfigJson(json, collapserKey, collapserConfig);
    }
    json.writeEndObject();
    json.writeEndObject();
    json.close();

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

From source file:net.sf.jabref.gui.mergeentries.MergeEntries.java

/**
 * Update the merged BibEntry with source and preview panel every time something is changed
 *//*w  ww . j a va2 s  .  c o m*/
private void updateAll() {
    if (!doneBuilding) {
        // If we are not done adding everything, do not do anything...
        return;
    }
    // Check if the type has changed
    if (!identicalTypes && typeRadioButtons.get(0).isSelected()) {
        mergedEntry.setType(leftEntry.getType());
    } else {
        mergedEntry.setType(rightEntry.getType());
    }

    // Check the potentially different fields
    for (String field : differentFields) {
        if (radioButtons.get(field).get(0).isSelected()) {
            mergedEntry.setField(field, leftEntry.getFieldOptional(field).get()); // Will only happen if field exists
        } else if (radioButtons.get(field).get(2).isSelected()) {
            mergedEntry.setField(field, rightEntry.getFieldOptional(field).get()); // Will only happen if field exists
        } else {
            mergedEntry.clearField(field);
        }
    }

    // Update the PreviewPanel
    entryPreview.setEntry(mergedEntry);

    // Update the BibTeX source view
    StringWriter writer = new StringWriter();
    try {
        new BibEntryWriter(
                new LatexFieldFormatter(LatexFieldFormatterPreferences.fromPreferences(Globals.prefs)), false)
                        .write(mergedEntry, writer, databaseType);
    } catch (IOException ex) {
        LOGGER.error("Error in entry", ex);
    }
    sourceView.setText(writer.getBuffer().toString());
    sourceView.setCaretPosition(0);
}

From source file:nl.nn.adapterframework.util.XmlUtils.java

public static String transformXml(Transformer t, Source s) throws TransformerException, IOException {

    StringWriter out = new StringWriter(getBufSize());
    transformXml(t, s, out);/*from   w  w  w  . jav a2s  .  c  o m*/
    out.close();

    return (out.getBuffer().toString());

}

From source file:org.jfrog.build.client.ArtifactoryBuildInfoClient.java

String toJsonString(Object object) throws IOException {
    JsonFactory jsonFactory = httpClient.createJsonFactory();
    StringWriter writer = new StringWriter();
    JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(writer);
    jsonGenerator.useDefaultPrettyPrinter();
    jsonGenerator.writeObject(object);//from   w  ww. j av a  2s  .  c om
    String result = writer.getBuffer().toString();
    return result;
}

From source file:com.cts.ptms.carrier.ups.UPSHTTPClient.java

/**
 * This method triggers the shipping label generation process
 *//* ww w .j av  a  2  s. c  o  m*/
public ShipmentOrder generateShippingLabel(ShippingInfoDO shippingInfoDO, ShipmentRequest request)
        throws Exception {

    //Load the properties file 
    loadProperties();

    // JAXB Context of AccessRequest.java
    JAXBContext accessRequestJAXBC = JAXBContext.newInstance(AccessRequest.class.getPackage().getName());
    Marshaller accessRequestMarshaller = accessRequestJAXBC.createMarshaller();

    //JAXB Context of ShipmentConfirmRequest.java
    JAXBContext shipConfirmRequestJAXBC = JAXBContext.newInstance(ShipmentConfirmRequest.class);
    Marshaller shipConfirmRequestMarshaller = shipConfirmRequestJAXBC.createMarshaller();

    //JAXB Context of ShipmentConfirmResponse.java
    JAXBContext shipConfirmJAXBC = JAXBContext.newInstance(ShipmentConfirmResponse.class);
    Unmarshaller shipConfirmUnmarshaller = shipConfirmJAXBC.createUnmarshaller();

    //JAXB Context of ShipmentAcceptRequest.java
    JAXBContext shipAcceptJaxb = JAXBContext.newInstance(ShipmentAcceptRequest.class);
    Marshaller shipAcceptRequestMarshaller = shipAcceptJaxb.createMarshaller();

    //JAXB Context of ShipmentAcceptResponse.Java
    JAXBContext shipAcceptAXBC = JAXBContext.newInstance(ShipmentAcceptResponse.class);
    Unmarshaller shipAcceptUnmarshaller = shipAcceptAXBC.createUnmarshaller();

    StringWriter strWriter = new StringWriter();
    accessRequestMarshaller.marshal(shippingInfoDO.getUpsSecurity(), strWriter);
    shipConfirmRequestMarshaller.marshal(shippingInfoDO.getConfirmRequest(), strWriter);
    strWriter.flush();
    strWriter.close();
    String confirmInput = strWriter.getBuffer().toString();
    //--confirmInput = confirmInput.replace(ShippingConstants.XML_NAMESPACE, "");
    String strResults = contactService(confirmInput,
            properties.getProperty(ShippingConstants.SHIPPING_CONFIRM_URL));
    //--strResults = strResults.replace(ShippingConstants.SHIP_Response_TAG,ShippingConstants.ship_Response_Replace);
    String result = "";
    if (strResults.indexOf(ShippingConstants.error_Open_tag) != -1) {
        result = strResults.substring(strResults.indexOf(ShippingConstants.error_Open_tag),
                strResults.indexOf(ShippingConstants.error_Close_tag));
        result = result.replace(ShippingConstants.error_Open_tag, "");
    }
    ByteArrayInputStream input = new ByteArrayInputStream(strResults.getBytes());
    ShipmentConfirmResponse shipconfirmResponse = new ShipmentConfirmResponse();
    if (null != shipconfirmResponse.getResponse()) {
        shipconfirmResponse.getResponse().getError().add(new Error());
    }
    shipconfirmResponse = (ShipmentConfirmResponse) shipConfirmUnmarshaller.unmarshal(input);
    if (shipconfirmResponse.getResponse().getResponseStatusCode().equals("1")) {
        com.cts.ptms.model.accept.request.ObjectFactory acceptObjectFactory = new com.cts.ptms.model.accept.request.ObjectFactory();
        //ShipmentAcceptRequestObjectFactory acceptObjectFactory = new ShipmentAcceptRequestObjectFactory();
        ShipmentAcceptRequest shipAcceptRequest = acceptObjectFactory.createShipmentAcceptRequest();
        ShipmentAcceptRequest shipmentAcceptRequest = populateShipAcceptRequest(shipAcceptRequest,
                shipconfirmResponse);

        StringWriter strWriterResponse = new StringWriter();
        accessRequestMarshaller.marshal(shippingInfoDO.getUpsSecurity(), strWriterResponse);
        shipAcceptRequestMarshaller.marshal(shipmentAcceptRequest, strWriterResponse);
        strWriterResponse.flush();
        strWriterResponse.close();
        String acceptInput = strWriterResponse.getBuffer().toString();
        //--acceptInput = acceptInput.replace(ShippingConstants.XML_NAMESPACE, "");
        String strAcceptResults = contactService(acceptInput,
                properties.getProperty(ShippingConstants.SHIPPING_ACCEPT_URL));
        //--strAcceptResults = strAcceptResults.replace(ShippingConstants.SHIP_Accept_TAG,ShippingConstants.ship_Accept_Replace);
        ByteArrayInputStream inputAccept = new ByteArrayInputStream(strAcceptResults.getBytes());
        Object objectAccept = shipAcceptUnmarshaller.unmarshal(inputAccept);
        ShipmentAcceptResponse shipAcceptResponse = (ShipmentAcceptResponse) objectAccept;
        if (!shipAcceptResponse.getResponse().getResponseStatusDescription().equalsIgnoreCase("FAILURE")) {
            String imageSrc = shipAcceptResponse.getShipmentResults().getPackageResults().get(0).getLabelImage()
                    .getGraphicImage();
            byte[] decoded = Base64.getDecoder().decode(imageSrc);
            generateShippingLabelPDF(decoded,
                    shipAcceptResponse.getShipmentResults().getShipmentIdentificationNumber(), shippingInfoDO,
                    request);
            if (null != shipAcceptResponse.getShipmentResults().getForm()) {
                String formInfo = shipAcceptResponse.getShipmentResults().getForm().getImage()
                        .getGraphicImage();
                String formExtn = shipAcceptResponse.getShipmentResults().getForm().getImage().getImageFormat()
                        .getCode();
                String formDocType = shipAcceptResponse.getShipmentResults().getForm().getClass()
                        .getSimpleName();
                byte[] intlForms = Base64.getDecoder().decode(formInfo);
                generateShippingForms(intlForms,
                        shipAcceptResponse.getShipmentResults().getShipmentIdentificationNumber(), formDocType,
                        formExtn);
            }
            return createShipmentResposeObj(null, shipAcceptResponse);
        } else {
            return createShipmentResposeObj(null, shipAcceptResponse);
        }
    } else {
        shipconfirmResponse.getResponse().getError().get(0).setErrorDescription(result);
        return createShipmentResposeObj(shipconfirmResponse, null);
    }
}

From source file:org.apache.axis.encoding.DeserializerImpl.java

/**
  * onEndElement is called by endElement.  It is not called
  * if the element has an href.// w w  w. j a  va2  s  .co  m
  * @param namespace is the namespace of the child element
  * @param localName is the local name of the child element
  * @param context is the deserialization context
  */
public void onEndElement(String namespace, String localName, DeserializationContext context)
        throws SAXException {
    // If we only have SAX events, but someone really wanted a
    // value, try sending them the contents of this element
    // as a String...
    // ??? Is this the right thing to do here?

    if (this.getClass().equals(DeserializerImpl.class) && targets != null && !targets.isEmpty()) {
        StringWriter writer = new StringWriter();
        SerializationContext serContext = new SerializationContext(writer, context.getMessageContext());
        serContext.setSendDecl(false);

        SAXOutputter so = null;
        so = new SAXOutputter(serContext);
        context.getCurElement().publishContents(so);
        if (!isNil) {
            value = writer.getBuffer().toString();
        }
    }
}

From source file:org.terasoluna.gfw.web.token.transaction.TransactionTokenTagTest.java

/**
 * TransactionToken is not null/* ww  w .  j  av a  2  s . com*/
 */
@Test
public void testWriteTagContentTagWriter02() {

    // setup arguments
    TransactionTokenTag tag = new TransactionTokenTag();
    PageContext pageContext = mock(PageContext.class);
    tag.setPageContext(pageContext);
    HttpServletRequest request = mock(HttpServletRequest.class);
    TransactionToken token = new TransactionToken("tokenName", "tokenkey", "tokenValue");
    StringWriter sw = new StringWriter();
    TagWriter tagWriter = new TagWriter(sw);

    // mock behavior
    when((HttpServletRequest) pageContext.getRequest()).thenReturn(request);
    when((TransactionToken) request.getAttribute(TransactionTokenInterceptor.NEXT_TOKEN_REQUEST_ATTRIBUTE_NAME))
            .thenReturn(token);

    // run
    int result = 1;
    try {
        result = tag.writeTagContent(tagWriter);
    } catch (JspException e) {
        fail();
    }

    // capture
    String expected = "<input type=\"hidden\" name=\"" + TransactionTokenInterceptor.TOKEN_REQUEST_PARAMETER
            + "\" value=\"" + token.getTokenString() + "\"/>";

    // assert
    assertThat(sw.getBuffer().toString(), is(expected));
    assertThat(result, is(0));
}

From source file:org.openmrs.module.sdmxhddataexport.web.controller.report.ReportDataElementController.java

public String transform(String str) throws Exception {
    try {//from  w  w  w.ja  va2 s . co m
        //String XMLFileName = "src\\cdcatalog.xml";
        //String OutputFileName = "src\\myResult.html";
        //  String StyleFileName = "/media/xml-to-string.xsl";
        InputStream inpXsl = OpenmrsClassLoader.getInstance().getResourceAsStream("xml-to-string.xsl");

        XMLReader reader = XMLReaderFactory.createXMLReader();
        InputStream inp = new ByteArrayInputStream(str.getBytes());
        Source source = new SAXSource(reader, new InputSource(inp));
        //Source source2 = new SAXSource(reader, new InputSource(StyleFileName));
        //ContentHandler theHandler = new MyHandler();
        StringWriter outWriter = new StringWriter();
        StreamResult result = new StreamResult(outWriter);
        //Result result = new StreamResult(OutputFileName);
        //          InputStream stinp=new ByteArrayInputStream(styleText.getBytes());         
        Source style = new StreamSource(inpXsl);

        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer trans = transFactory.newTransformer(style);

        trans.transform(source, result);
        String s = outWriter.getBuffer().toString();
        System.out.println(s);
        return s;
    } catch (SAXException e) {
        System.out.println(e.getMessage());
        return e.getMessage();
    }
}

From source file:guru.qas.martini.jmeter.sampler.DefaultStepResultMarshaller.java

@Override
public String getJson(StepResult result) throws IOException {
    StringWriter writer = new StringWriter();

    try (JsonWriter jsonWriter = gson.newJsonWriter(writer)) {
        jsonWriter.beginObject();/*from  ww  w .j av a 2 s  .  com*/
        jsonWriter.name("step");
        jsonWriter.beginObject();

        Delegate delegate = new Delegate(result, jsonWriter);
        delegate.addStartTimestamp();
        delegate.addEndTimestamp();
        delegate.addKeyword();
        delegate.addText();
        delegate.addLine();
        delegate.addMethod();
        delegate.addStatus();
        delegate.addException();
        delegate.addEmbedded();

        jsonWriter.endObject();
        jsonWriter.endObject();
    }

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

From source file:com.duroty.lucene.parser.PdfBoxParser.java

/**
 * DOCUMENT ME!/*w w  w.j  a v a 2s. c  o  m*/
 *
 * @return DOCUMENT ME!
 *
 * @throws ParserException DOCUMENT ME!
 * @throws IOException DOCUMENT ME!
 */
private String parse() throws ParserException {
    PDDocument pdfDocument = null;
    StringWriter writer = null;

    try {
        pdfDocument = PDDocument.load(input);

        if (pdfDocument.isEncrypted()) {
            //Just try using the default password and move on
            pdfDocument.decrypt("");
        }

        //create a writer where to append the text content.
        writer = new StringWriter();

        PDFTextStripper stripper = new PDFTextStripper();
        stripper.writeText(pdfDocument, writer);

        // Note: the buffer to string operation is costless;
        // the char array value of the writer buffer and the content string
        // is shared as long as the buffer content is not modified, which will
        // not occur here.
        return writer.getBuffer().toString();
    } catch (CryptographyException e) {
    } catch (InvalidPasswordException e) {
    } catch (IOException e) {
    } finally {
        if (pdfDocument != null) {
            try {
                pdfDocument.close();
            } catch (IOException e) {
            }
        }

        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(writer);
    }

    return null;
}