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:de.micromata.genome.gwiki.page.impl.GWikiPropsDescriptorValue.java

/**
 * Render.//from   w  ww. j  a  v  a 2  s .  c o m
 *
 * @param editor the editor
 * @param pct the pct
 * @return the string
 */
public String render(GWikiPropsEditorArtefakt<?> editor, PropsEditContext pct) {
    StringWriter sout = new StringWriter();
    pct.getWikiContext().getCreatePageContext().pushBody(sout);
    if (pct.invokeOnControlerBean("onRender") == false) {
        editor.onRenderInternal(pct);
    }
    pct.getWikiContext().getCreatePageContext().popBody();
    return sout.getBuffer().toString();
}

From source file:org.apache.asterix.event.service.ZooKeeperService.java

private Pair<CharSequence, CharSequence> getProcessStreams(Process process) throws IOException {
    StringWriter stdout = new StringWriter();
    StringWriter stderr = new StringWriter();
    IOUtils.copy(process.getInputStream(), stdout, Charset.defaultCharset());
    IOUtils.copy(process.getErrorStream(), stderr, Charset.defaultCharset());
    return new ImmutablePair<>(stdout.getBuffer(), stderr.getBuffer());
}

From source file:com.janoz.usenet.processors.impl.WebbasedProcessor.java

protected String responseAsString(InputStream responseStream) {
    StringWriter sw = new StringWriter();
    int i;//www.  ja  v a  2s  .c o  m
    try {
        while ((i = responseStream.read()) >= 0) {
            sw.write(i);
        }
    } catch (IOException e) {
        LOG.error("Error reading response.", e);
        throw new RetrieveException("Error reading response.", e);
    }
    String result = sw.getBuffer().toString().trim();
    return result;
}

From source file:omero.util.IceMapper.java

public static String stackAsString(Throwable t) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    t.printStackTrace(pw);//from w w  w .j  a va  2s.co m
    Throwable cause = t.getCause();
    while (cause != null && cause != t) {
        cause.printStackTrace(pw);
        t = cause;
        cause = t.getCause();
    }
    pw.flush();
    pw.close();

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

From source file:org.opencastproject.workflow.handler.mediapackagepost.MediaPackagePostOperationHandler.java

/** Serialize XML Document to string
 *
 * @param doc/* w w  w.ja v a2 s  .c om*/
 * @return
 * @throws Exception
 */
private String xmlToString(Document doc) throws Exception {
    Source source = new DOMSource(doc);
    StringWriter stringWriter = new StringWriter();
    Result result = new StreamResult(stringWriter);
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.transform(source, result);
    return stringWriter.getBuffer().toString();
}

From source file:Repackage.java

StringBuffer readInputStream(InputStream is) throws IOException {
    Reader r = new InputStreamReader(is);
    StringWriter w = new StringWriter();

    copy(r, w);/*from  w w w . java 2 s  .  c  o m*/

    w.close();
    r.close();

    return w.getBuffer();
}

From source file:nz.co.senanque.base.ObjectTest.java

@SuppressWarnings("unused")
@Test//from   ww w . j a  va  2 s .c  om
public void test1() throws Exception {
    ValidationSession validationSession = m_validationEngine.createSession();

    // create a customer
    Customer customer = m_customerDAO.createCustomer();
    validationSession.bind(customer);
    Invoice invoice = new Invoice();
    invoice.setDescription("test invoice");
    customer.getInvoices().add(invoice);
    boolean exceptionFound = false;
    try {
        customer.setName("ttt");
    } catch (ValidationException e) {
        exceptionFound = true;
    }
    assertTrue(exceptionFound);

    final ObjectMetadata customerMetadata = validationSession.getMetadata(customer);
    final FieldMetadata customerTypeMetadata = customerMetadata.getFieldMetadata(Customer.CUSTOMERTYPE);

    assertFalse(customerTypeMetadata.isActive());
    assertFalse(customerTypeMetadata.isReadOnly());
    assertFalse(customerTypeMetadata.isRequired());

    customer.setName("aaaab");
    assertTrue(customerTypeMetadata.isActive());
    assertTrue(customerTypeMetadata.isReadOnly());
    assertTrue(customerTypeMetadata.isRequired());
    exceptionFound = false;
    try {
        customer.setCustomerType("B");
    } catch (Exception e) {
        exceptionFound = true;
    }
    assertTrue(exceptionFound);
    exceptionFound = false;
    try {
        customer.setCustomerType("XXX");
    } catch (Exception e) {
        exceptionFound = true;
    }
    assertTrue(exceptionFound);
    customer.setBusiness(IndustryType.AG);
    customer.setAmount(new Double(500.99));
    final long id = m_customerDAO.save(customer);
    log.info(id);

    // fetch customer back
    customer = m_customerDAO.getCustomer(id);
    final int invoiceCount = customer.getInvoices().size();
    validationSession.bind(customer);
    invoice = new Invoice();
    invoice.setDescription("test invoice2");
    customer.getInvoices().add(invoice);
    m_customerDAO.save(customer);

    // fetch customer again
    customer = m_customerDAO.getCustomer(id);
    customer.toString();
    validationSession.bind(customer);
    final Invoice inv = customer.getInvoices().get(0);
    customer.getInvoices().remove(inv);

    //ObjectMetadata metadata = validationSession.getMetadata(customer);
    ObjectMetadata metadata = customer.getMetadata();
    org.junit.Assert.assertEquals("this is a description",
            metadata.getFieldMetadata(Customer.NAME).getDescription());
    List<ChoiceBase> choices = metadata.getFieldMetadata(Customer.BUSINESS).getChoiceList();
    assertEquals(1, choices.size());
    List<ChoiceBase> choices2 = metadata.getFieldMetadata(Customer.CUSTOMERTYPE).getChoiceList();
    assertEquals(2, choices2.size());
    choices2 = metadata.getFieldMetadata(Customer.CUSTOMERTYPE).getChoiceList();
    assertEquals(2, choices2.size());

    customer.setName("aab");
    choices2 = metadata.getFieldMetadata(Customer.CUSTOMERTYPE).getChoiceList();
    assertEquals(6, choices2.size());

    // Convert customer to XML
    QName qname = new QName("http://www.example.org/sandbox", "Session");
    JAXBElement<Session> sessionJAXB = new JAXBElement<Session>(qname, Session.class, new Session());
    sessionJAXB.getValue().getCustomers().add(customer); //??This fails to actually add
    StringWriter marshallWriter = new StringWriter();
    Result marshallResult = new StreamResult(marshallWriter);
    m_marshaller.marshal(sessionJAXB, marshallResult);
    marshallWriter.flush();
    String result = marshallWriter.getBuffer().toString().trim();
    String xml = result.replaceAll("\\Qhttp://www.example.org/sandbox\\E", "http://www.example.org/sandbox");
    log.info(xml);

    // Convert customer back to objects
    SAXBuilder builder = new SAXBuilder();
    org.jdom.Document resultDOM = builder.build(new StringReader(xml));
    @SuppressWarnings("unchecked")
    JAXBElement<Session> request = (JAXBElement<Session>) m_unmarshaller.unmarshal(new JDOMSource(resultDOM));
    validationSession = m_validationEngine.createSession();
    validationSession.bind(request.getValue());
    assertEquals(3, validationSession.getProxyCount());
    List<Customer> customers = request.getValue().getCustomers();
    assertEquals(1, customers.size());
    customers.clear();
    assertEquals(1, validationSession.getProxyCount());
    request.toString();
    validationSession.close();
}

From source file:edu.northwestern.bioinformatics.studycalendar.grid.PSCStudyService.java

@Transactional(readOnly = false)
public edu.northwestern.bioinformatics.studycalendar.grid.Study createStudy(
        edu.northwestern.bioinformatics.studycalendar.grid.Study gridStudy)
        throws RemoteException, StudyCreationException {

    if (gridStudy == null) {
        String message = "method parameter  is null";
        logger.error(message);//from  www  .j av a2s .co m
        StudyCreationException studyCreationException = new StudyCreationException();
        studyCreationException.setFaultString(message);
        studyCreationException.setFaultReason(message);
        throw studyCreationException;
    }
    StringWriter studyXml = new StringWriter();

    String studyDocumentXml = "";
    try {

        Utils.serializeObject(gridStudy,
                new javax.xml.namespace.QName("http://bioinformatics.northwestern.edu/ns/psc", "study",
                        XMLConstants.W3C_XML_SCHEMA_NS_URI),
                studyXml);

        logger.info("study xml:" + studyXml.toString());

        studyDocumentXml = studyXml.getBuffer().toString();

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(studyDocumentXml.getBytes());

        studyXMLReader.readAndSave(byteArrayInputStream);

    } catch (StudyCalendarValidationException exception) {
        String message = "error while importing the study:studyXml-" + studyDocumentXml + " exception message:"
                + exception.getMessage();
        logger.error(message);
        StudyCreationException studyCreationException = new StudyCreationException();
        studyCreationException.setFaultString(message);
        studyCreationException.setFaultReason(message);
        throw studyCreationException;

    } catch (Exception e) {
        String message = "error while importing the study:assigned_identifier="
                + gridStudy.getAssignedIdentifier() + " exception message:" + e.getMessage();
        logger.error(message);
        throw new RemoteException(message);

    }

    return null;
}

From source file:org.apache.falcon.converter.AbstractOozieEntityMapper.java

protected void marshal(Cluster cluster, JAXBElement<?> jaxbElement, JAXBContext jaxbContext, Path outPath)
        throws FalconException {
    try {//from  ww w .j a v  a  2 s. c o  m
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        FileSystem fs = HadoopClientFactory.get().createFileSystem(outPath.toUri(),
                ClusterHelper.getConfiguration(cluster));
        OutputStream out = fs.create(outPath);
        try {
            marshaller.marshal(jaxbElement, out);
        } finally {
            out.close();
        }
        if (LOG.isDebugEnabled()) {
            StringWriter writer = new StringWriter();
            marshaller.marshal(jaxbElement, writer);
            LOG.debug("Writing definition to " + outPath + " on cluster " + cluster.getName());
            LOG.debug(writer.getBuffer());
        }

        LOG.info("Marshalled " + jaxbElement.getDeclaredType() + " to " + outPath);
    } catch (Exception e) {
        throw new FalconException("Unable to marshall app object", e);
    }
}

From source file:org.hexlogic.CooptoPluginFactory.java

@Override
public List<?> findChildrenInRelation(InventoryRef parent, String relationName) {
    log.debug("running findChildrenInRelation() with parent=" + parent + " and relationName=" + relationName
            + ".");

    if (parent.isOfType(CooptoModuleBuilder.ROOT)) {
        log.debug("parent is of type " + CooptoModuleBuilder.ROOT);
        if (relationName.equals(CooptoModuleBuilder.NODERELATION)) {
            log.debug("relation is " + CooptoModuleBuilder.NODERELATION);
            return findAll(DockerNode.TYPE, null).getElements();
        } else {/*from  w  w w . j a va2  s  .  co  m*/
            throw new IndexOutOfBoundsException("Unknown relation name: " + relationName);
        }
    } else if (parent.isOfType(DockerNode.TYPE)) {
        log.debug("parent is of type " + DockerNode.TYPE + ". Searching...");

        try {
            // try to find in cache - must be in synchronized block
            synchronized (nodes) {
                Iterator<DockerNode> itr = nodes.iterator();
                while (itr.hasNext()) {
                    DockerNode node = itr.next();
                    if (node.getId().equals(parent.getId())) {
                        log.debug("Found parent " + DockerNode.TYPE + " with id " + parent.getId());
                        if (relationName.equals(DockerNode.IMAGERELATION)) {
                            log.debug("Relation is " + DockerNode.IMAGERELATION);
                            if (node != null) {
                                return node.getImages();
                            }
                        } else if (relationName.equals(DockerNode.CONTAINERRELATION)) {
                            log.debug("Relation is " + DockerNode.CONTAINERRELATION);
                            if (node != null) {
                                return node.getContainers();
                            }
                        } else {
                            throw new IndexOutOfBoundsException("Unknown relation name: " + relationName);
                        }
                    }
                }
            }
        } catch (Exception e) {
            final StringWriter sw = new StringWriter();
            final PrintWriter pw = new PrintWriter(sw, true);
            e.printStackTrace(pw);
            log.error("Error: " + sw.getBuffer().toString());
        }
    }
    log.warn("Warning: no such parent object or relation was found");
    return Collections.emptyList();
}