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.hexlogic.model.DockerNodeService.java

public Collection<IEndpointConfiguration> getNodes() {
    log.debug("Running getNodes() and loading nodes from vCO EndpointConfiguration...");
    try {//from   w  w w . j av  a2s  .  c o  m
        Collection<IEndpointConfiguration> endpointConfigurations = service.getEndpointConfigurations();
        if (endpointConfigurations != null && !endpointConfigurations.isEmpty()) {
            log.debug(endpointConfigurations.size()
                    + " nodes are currently stored within the vCO EndpointConfiguration. Returning...");
            log.debug("Finished running getNodes().");
            return endpointConfigurations;
        }
    } catch (IOException e) {
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);
        log.error("Error: " + sw.getBuffer().toString());
    }
    log.debug("Finished running getNodes().");
    return Collections.emptyList();
}

From source file:net.frontlinesms.plugins.forms.FormsPluginController.java

/**
 * Fabaris_a.zanchi Method to remove empty groups for outgoing messages so
 * that mobile tool doesn't crash/*w  w w  .  ja  v  a  2  s  .c  o m*/
 *
 * @param content an xml document (just xml without any additional content)
 * @return xml document without empty groups with attribute
 * appearance="field-list"
 * @throws Exception
 */
public static String removeEmptyGroups(String content) throws Exception {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    InputSource inStream = new InputSource();
    inStream.setCharacterStream(new StringReader(content));
    org.w3c.dom.Document xmlDoc = docBuilder.parse(inStream);
    xmlDoc.getDocumentElement().normalize();
    NodeList groupList = xmlDoc.getElementsByTagName("group");
    int i = 0;
    while (i < groupList.getLength()) {
        Element group = (Element) groupList.item(i);
        if (group.getAttribute("appearance").equals("field-list")) {
            if (group.getChildNodes().getLength() == 0) {
                groupList.item(i).getParentNode().removeChild(groupList.item(i));
                i--;
            }
            if (group.getTextContent().equals(", ")) {
                groupList.item(i).getParentNode().removeChild(groupList.item(i));
                i--;
            }
        }
        i++;
    }
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer trans = tFactory.newTransformer();
    trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    StringWriter sWriter = new StringWriter();
    Result result = new StreamResult(sWriter);
    trans.transform(new DOMSource(xmlDoc), result);
    String result2 = sWriter.getBuffer().toString();
    System.out.println("---------- remove empty groups ---------");
    System.out.println(result2);
    return result2;
}

From source file:siia.booking.domain.trip.LegQuoteMarshallingTest.java

@Test
public void testMarshallingLeg() throws Exception {
    StringWriter writer = new StringWriter();
    StreamResult res = new StreamResult(writer);
    marshaller.marshal(this.exampleLegQuote, res);
    assertXMLEqual("Leg quote marshalling incorrect", exampleQuoteXml, writer.getBuffer().toString());
}

From source file:javolution.xml.XmlTest.java

public void testRock() throws XMLStreamException {
    final XMLBinding jc = new JCBinding();
    final String xml;
    {//from  www  . j  a v  a 2  s. c o  m
        final XMLObjectWriter wri = new XMLObjectWriter().setBinding(jc);
        final StringWriter bout = new StringWriter();
        wri.setOutput(bout);
        wri.write(new RockDouble(1, 2, 3));
        wri.close();
        xml = bout.getBuffer().toString();
        assertEquals("<?xml version=\"1.0\" ?><rock x=\"1.0\" y=\"2.0\" a=\"3.0\"/>", xml);

    }
    {
        final XMLObjectReader rea = new XMLObjectReader().setBinding(jc);
        rea.setInput(new StringReader(xml));
        final RockDouble r = rea.read();
        assertEquals("[1.0, 2.0, 3.0]", r.toString());
    }
}

From source file:net.frontlinesms.plugins.forms.FormsPluginController.java

/**
 * Fabaris_a.zanchi This method inserts the designer software version number
 * in the outgoing xform It also creates an empty tag for the client version
 *
 * @param xmlContent the string representation of the xform
 *//*from  ww w  .  j  a  v  a  2  s  . c  o m*/
public static String insertSoftwareVersionNumber(String xmlContent, Form form) throws Exception {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    InputSource inStream = new InputSource();
    inStream.setCharacterStream(new StringReader(xmlContent));
    org.w3c.dom.Document xmlDoc = docBuilder.parse(inStream);
    xmlDoc.getDocumentElement().normalize();
    Node versionNode = xmlDoc.getElementsByTagName(DefaultComponentDescriptor.DESINGER_VERSION_TAGNAME + "_"
            + DefaultComponentDescriptor.DESIGNER_VERSION_INDEX).item(0);
    if (versionNode != null) {
        versionNode.setTextContent(form.getDesignerVersion());
    }
    /*
     * NodeList nodeList = xmlDoc.getElementsByTagName("h:head"); Node
     * headNode = nodeList.item(0); Node modelNode =
     * xmlDoc.getElementsByTagName("model").item(0); Element newElemDesigner
     * = xmlDoc.createElement("designer_version"); Element newElemClient =
     * xmlDoc.createElement("client_version"); Node newNodeDesigner = (Node)
     * newElemDesigner; Node newNodeClient = (Node) newElemClient; String
     * designerVersion = form.getDesignerVersion(); if (designerVersion ==
     * null) designerVersion = "";
     * newNodeDesigner.appendChild(xmlDoc.createTextNode(designerVersion));
     * newNodeClient.appendChild(xmlDoc.createTextNode(""));
     * headNode.insertBefore(newNodeDesigner, modelNode);
     * headNode.insertBefore(newNodeClient, modelNode);
     */
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer trans = tFactory.newTransformer();
    trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    StringWriter sWriter = new StringWriter();
    Result result = new StreamResult(sWriter);
    trans.transform(new DOMSource(xmlDoc), result);
    String result2 = sWriter.getBuffer().toString();
    System.out.println("-------- inserting version ------------");
    System.out.println(result2);
    return result2;
}

From source file:grails.plugin.springsecurity.web.filter.DebugFilter.java

protected void log(boolean dumpStack, String message, Object... args) {
    StringBuilder output = new StringBuilder(256);
    output.append("\n\n************************************************************\n\n");
    output.append(message).append("\n");

    if (dumpStack) {
        StringWriter os = new StringWriter();
        GrailsUtil.deepSanitize(new Exception()).printStackTrace(new PrintWriter(os));
        StringBuffer buffer = os.getBuffer();
        // Remove the exception in case it scares people.
        int start = buffer.indexOf("java.lang.Exception");
        buffer.replace(start, start + 19, "");
        output.append("\nCall stack: \n").append(os);
    }// ww w  .  j  av a 2s  .c  o  m

    output.append("\n\n************************************************************\n\n");
    log.info(output.toString(), args);
}

From source file:edu.uci.ics.asterix.event.management.EventExecutor.java

public void executeEvent(Node node, String script, List<String> args, boolean isDaemon, Cluster cluster,
        Pattern pattern, IOutputHandler outputHandler, AsterixEventServiceClient client) throws IOException {
    List<String> pargs = new ArrayList<String>();
    pargs.add("/bin/bash");
    pargs.add(client.getEventsHomeDir() + File.separator + AsterixEventServiceUtil.EVENT_DIR + File.separator
            + EXECUTE_SCRIPT);/*  w ww.  j  a  v  a2 s .  c o  m*/
    StringBuffer envBuffer = new StringBuffer(IP_LOCATION + "=" + node.getClusterIp() + " ");
    boolean isMasterNode = node.getId().equals(cluster.getMasterNode().getId());

    if (!node.getId().equals(EventDriver.CLIENT_NODE_ID) && cluster.getEnv() != null) {
        for (Property p : cluster.getEnv().getProperty()) {
            if (p.getKey().equals("JAVA_HOME")) {
                String val = node.getJavaHome() == null ? p.getValue() : node.getJavaHome();
                envBuffer.append(p.getKey() + "=" + val + " ");
            } else if (p.getKey().equals(EventUtil.NC_JAVA_OPTS)) {
                if (!isMasterNode) {
                    StringBuilder builder = new StringBuilder();
                    builder.append("\"");
                    String javaOpts = p.getValue();
                    if (javaOpts != null) {
                        builder.append(javaOpts);
                    }
                    if (node.getDebugPort() != null) {
                        int debugPort = node.getDebugPort().intValue();
                        if (!javaOpts.contains("-Xdebug")) {
                            builder.append(
                                    (" " + "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address="
                                            + debugPort));
                        }
                    }
                    builder.append("\"");
                    envBuffer.append("JAVA_OPTS" + "=" + builder + " ");
                }
            } else if (p.getKey().equals(EventUtil.CC_JAVA_OPTS)) {
                if (isMasterNode) {
                    StringBuilder builder = new StringBuilder();
                    builder.append("\"");
                    String javaOpts = p.getValue();
                    if (javaOpts != null) {
                        builder.append(javaOpts);
                    }
                    if (node.getDebugPort() != null) {
                        int debugPort = node.getDebugPort().intValue();
                        if (!javaOpts.contains("-Xdebug")) {
                            builder.append(
                                    (" " + "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address="
                                            + debugPort));
                        }
                    }
                    builder.append("\"");
                    envBuffer.append("JAVA_OPTS" + "=" + builder + " ");
                }
            } else if (p.getKey().equals("LOG_DIR")) {
                String val = node.getLogDir() == null ? p.getValue() : node.getLogDir();
                envBuffer.append(p.getKey() + "=" + val + " ");
            } else {
                envBuffer.append(p.getKey() + "=" + p.getValue() + " ");
            }

        }
        pargs.add(cluster.getUsername() == null ? System.getProperty("user.name") : cluster.getUsername());
    }

    StringBuffer argBuffer = new StringBuffer();
    if (args != null && args.size() > 0) {
        for (String arg : args) {
            argBuffer.append(arg + " ");
        }
    }

    ProcessBuilder pb = new ProcessBuilder(pargs);
    pb.environment().put(IP_LOCATION, node.getClusterIp());
    pb.environment().put(CLUSTER_ENV, envBuffer.toString());
    pb.environment().put(SCRIPT, script);
    pb.environment().put(ARGS, argBuffer.toString());
    pb.environment().put(DAEMON, isDaemon ? "true" : "false");

    Process p = pb.start();
    if (!isDaemon) {
        BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
        StringWriter writer = new StringWriter();
        IOUtils.copy(bis, writer, "UTF-8");
        String result = writer.getBuffer().toString();
        OutputAnalysis analysis = outputHandler.reportEventOutput(pattern.getEvent(), result);
        if (!analysis.isExpected()) {
            throw new IOException(analysis.getErrorMessage() + result);
        }
    }
}

From source file:javolution.xml.XmlTest.java

public void testRockSet() throws XMLStreamException {
    final XMLBinding jc = new JCBinding();
    final String xml;
    {/*from w ww  .  j av a  2 s  . c om*/
        final XMLObjectWriter wri = new XMLObjectWriter().setBinding(jc);
        final StringWriter bout = new StringWriter();
        wri.setOutput(bout);
        wri.write(RockSetUtils.allHome());
        wri.close();
        xml = bout.getBuffer().toString();
        assertEquals(
                "<?xml version=\"1.0\" ?><rockset><dark class=\"[Lorg.jcurl.core.api.Rock;\" componentType=\"org.jcurl.core.api.Rock\" length=\"8\"><rock x=\"-2.2098000049591064\" y=\"9.448800086975097\" a=\"0.0\"/><rock x=\"-2.2098000049591064\" y=\"9.083040237426757\" a=\"0.0\"/><rock x=\"-2.2098000049591064\" y=\"8.717280387878418\" a=\"0.0\"/><rock x=\"-2.2098000049591064\" y=\"8.351519584655761\" a=\"0.0\"/><rock x=\"-2.2098000049591064\" y=\"7.98576021194458\" a=\"0.0\"/><rock x=\"-2.2098000049591064\" y=\"7.619999885559082\" a=\"0.0\"/><rock x=\"-2.2098000049591064\" y=\"7.254240036010742\" a=\"0.0\"/><rock x=\"-2.2098000049591064\" y=\"6.888480186462402\" a=\"0.0\"/></dark><light class=\"[Lorg.jcurl.core.api.Rock;\" componentType=\"org.jcurl.core.api.Rock\" length=\"8\"><rock x=\"2.2098000049591064\" y=\"9.448800086975097\" a=\"0.0\"/><rock x=\"2.2098000049591064\" y=\"9.083040237426757\" a=\"0.0\"/><rock x=\"2.2098000049591064\" y=\"8.717280387878418\" a=\"0.0\"/><rock x=\"2.2098000049591064\" y=\"8.351519584655761\" a=\"0.0\"/><rock x=\"2.2098000049591064\" y=\"7.98576021194458\" a=\"0.0\"/><rock x=\"2.2098000049591064\" y=\"7.619999885559082\" a=\"0.0\"/><rock x=\"2.2098000049591064\" y=\"7.254240036010742\" a=\"0.0\"/><rock x=\"2.2098000049591064\" y=\"6.888480186462402\" a=\"0.0\"/></light></rockset>",
                xml);

    }
    {
        final XMLObjectReader rea = new XMLObjectReader().setBinding(jc);
        rea.setInput(new StringReader(xml));
        try {
            rea.read();
            fail();
        } catch (final XMLStreamException e) {
            assertEquals(InstantiationException.class, e.getNestedException().getClass());
        }
    }
}

From source file:net.erdfelt.android.sdkfido.configer.ConfigCmdLineParserTest.java

private void assertContains(StringWriter capture, String content) {
    String buf = capture.getBuffer().toString();
    Assert.assertThat(buf, notNullValue());
    if (!buf.contains(content)) {
        Assert.fail("Expected a string \"" + content + "\"\n" + buf);
    }//  w  w w.j av a  2s  . c om
}

From source file:org.obiba.mica.dataset.service.KeyStoreService.java

@NotNull
public String getPEMCertificate(@NotNull String name, String alias) throws KeyStoreException, IOException {
    Certificate certificate = ofNullable(getKeyStore(name).getKeyStore().getCertificate(alias))
            .orElseThrow(() -> new IllegalArgumentException("Cannot find certificate for alias: " + alias));

    StringWriter writer = new StringWriter();
    PEMWriter pemWriter = new PEMWriter(writer);
    pemWriter.writeObject(certificate);/*from   w w w. j a  v a2s .c o m*/
    pemWriter.flush();

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