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.meltmedia.jackson.crypto.EncryptedJsonSerializer.java

@Override
public void serialize(Object object, JsonGenerator generator, SerializerProvider provider)
        throws IOException, JsonProcessingException {

    StringWriter writer = new StringWriter();
    JsonGenerator nestedGenerator = generator.getCodec().getFactory().createGenerator(writer);
    if (baseSer == null) {
        provider.defaultSerializeValue(object, nestedGenerator);
    } else {/* ww w  .  ja v  a  2 s  .c  om*/
        baseSer.serialize(object, nestedGenerator, provider);
    }
    nestedGenerator.close();
    String value = writer.getBuffer().toString();
    EncryptedJson encrypted = service.encrypt(value, this.annotation.encoding());
    generator.writeObject(encrypted);
}

From source file:com.thinkberg.webdav.data.DavResource.java

protected boolean setPropertyValue(Element root, Element propertyEl) {
    LogFactory.getLog(getClass()).debug(String.format("[%s].set('%s')", object.getName(), propertyEl.asXML()));

    if (!ALL_PROPERTIES.contains(propertyEl.getName())) {
        final String nameSpace = propertyEl.getNamespaceURI();
        final String attributeName = getFQName(nameSpace, propertyEl.getName());
        try {//from   w  w  w  .j a  va 2s  .  c om
            FileContent objectContent = object.getContent();
            final String command = propertyEl.getParent().getParent().getName();
            if (TAG_PROP_SET.equals(command)) {
                StringWriter propertyValueWriter = new StringWriter();
                propertyEl.write(propertyValueWriter);
                propertyValueWriter.close();
                objectContent.setAttribute(attributeName, propertyValueWriter.getBuffer().toString());
            } else if (TAG_PROP_REMOVE.equals(command)) {
                objectContent.setAttribute(attributeName, null);
            }
            root.addElement(propertyEl.getQName());
            return true;
        } catch (IOException e) {
            LogFactory.getLog(getClass()).error(String.format("can't store attribute property '%s' = '%s'",
                    attributeName, propertyEl.asXML()), e);
        }
    }
    return false;
}

From source file:com.chenchengzhi.windtalkers.server.WindMessageFactory.java

@Override
public HttpResponse serialize(Message message) throws IOException {
    Issue issue = message.get(Issue.class);

    if (issue != null) {
        return throwError(issue);
    }//from   w  ww . ja v  a 2  s  . c  om

    HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    ObjectNode response = message.getResponseBody();

    if (response != null) {
        httpResponse.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/json");
        StringWriter writer = new StringWriter();
        JsonGenerator generator = jsonFactory.createJsonGenerator(writer);
        generator.setPrettyPrinter(new DefaultPrettyPrinter());

        response.serialize(generator, new DefaultSerializerProvider.Impl());
        generator.flush();
        httpResponse.setContent(ChannelBuffers.copiedBuffer(writer.getBuffer(), Charsets.UTF_8));
    }

    httpResponse.setHeader(HttpHeaders.Names.CONTENT_LENGTH, httpResponse.getContent().readableBytes());
    return httpResponse;
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.spec.DuplicateGerritListenersPreloadedProjectHudsonTestCase.java

/**
 * Transforms the xml document into an xml string.
 *
 * @param doc the document/*from   w  w  w . j  av  a  2  s.  c o m*/
 * @return the xml
 * @throws TransformerException if so.
 */
String xmlToString(Document doc) throws TransformerException {
    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));
    return writer.getBuffer().toString();
}

From source file:org.apache.ode.bpel.runtime.ExtensionContextImpl.java

public void completeWithFault(String cid, Throwable t) {
    if (!hasCompleted) {
        StringWriter sw = new StringWriter();
        t.printStackTrace(new PrintWriter(sw));
        FaultData fault = new FaultData(new QName(Namespaces.WSBPEL2_0_FINAL_EXEC, "subLanguageExecutionFault"),
                _activityInfo.o, sw.getBuffer().toString());
        _context.completeExtensionActivity(cid, fault);
        hasCompleted = true;/*from   w  w w .j  a v a  2  s .  com*/
    } else {
        if (__log.isWarnEnabled()) {
            __log.warn("Activity '" + _activityInfo.o.name + "' has already been completed.");
        }
    }
}

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

protected void marshal(Cluster cluster, JAXBElement<?> jaxbElement, JAXBContext jaxbContext, Path outPath)
        throws IvoryException {
    try {//ww  w. j  a v a  2s  . c o  m
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        FileSystem fs = outPath.getFileSystem(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 IvoryException("Unable to marshall app object", e);
    }
}

From source file:org.apache.axis2.deployment.ServiceDeployer.java

public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {
    boolean isDirectory = deploymentFileData.getFile().isDirectory();
    ArchiveReader archiveReader;/* ww w.  ja  v  a2 s . c  o  m*/
    StringWriter errorWriter = new StringWriter();
    archiveReader = new ArchiveReader();
    String serviceStatus = "";
    try {
        deploymentFileData.setClassLoader(isDirectory, axisConfig.getServiceClassLoader(),
                (File) axisConfig.getParameterValue(Constants.Configuration.ARTIFACTS_TEMP_DIR),
                axisConfig.isChildFirstClassLoading());
        HashMap<String, AxisService> wsdlservice = archiveReader.processWSDLs(deploymentFileData);
        if (wsdlservice != null && wsdlservice.size() > 0) {
            for (AxisService service : wsdlservice.values()) {
                Iterator<AxisOperation> operations = service.getOperations();
                while (operations.hasNext()) {
                    AxisOperation axisOperation = operations.next();
                    axisConfig.getPhasesInfo().setOperationPhases(axisOperation);
                }
            }
        }
        AxisServiceGroup serviceGroup = new AxisServiceGroup(axisConfig);
        serviceGroup.setServiceGroupClassLoader(deploymentFileData.getClassLoader());
        ArrayList<AxisService> serviceList = archiveReader.processServiceGroup(
                deploymentFileData.getAbsolutePath(), deploymentFileData, serviceGroup, isDirectory,
                wsdlservice, configCtx);
        URL location = deploymentFileData.getFile().toURL();

        // Add the hierarchical path to the service group
        if (location != null) {
            String serviceHierarchy = Utils.getServiceHierarchy(location.getPath(), this.directory);
            if (serviceHierarchy != null && !"".equals(serviceHierarchy)) {
                serviceGroup.setServiceGroupName(serviceHierarchy + serviceGroup.getServiceGroupName());
                for (AxisService axisService : serviceList) {
                    axisService.setName(serviceHierarchy + axisService.getName());
                }
            }
        }
        DeploymentEngine.addServiceGroup(serviceGroup, serviceList, location, deploymentFileData, axisConfig);

        super.deploy(deploymentFileData);
    } catch (DeploymentException de) {
        de.printStackTrace();
        log.error(Messages.getMessage(DeploymentErrorMsgs.INVALID_SERVICE, deploymentFileData.getName(),
                de.getMessage()), de);
        PrintWriter error_ptintWriter = new PrintWriter(errorWriter);
        de.printStackTrace(error_ptintWriter);
        serviceStatus = "Error:\n" + errorWriter.toString();

        throw de;

    } catch (AxisFault axisFault) {
        log.error(Messages.getMessage(DeploymentErrorMsgs.INVALID_SERVICE, deploymentFileData.getName(),
                axisFault.getMessage()), axisFault);
        PrintWriter error_ptintWriter = new PrintWriter(errorWriter);
        axisFault.printStackTrace(error_ptintWriter);
        serviceStatus = "Error:\n" + errorWriter.toString();

        throw new DeploymentException(axisFault);

    } catch (Exception e) {
        if (log.isInfoEnabled()) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            log.info(Messages.getMessage(DeploymentErrorMsgs.INVALID_SERVICE, deploymentFileData.getName(),
                    sw.getBuffer().toString()));
        }
        PrintWriter error_ptintWriter = new PrintWriter(errorWriter);
        e.printStackTrace(error_ptintWriter);
        serviceStatus = "Error:\n" + errorWriter.toString();

        throw new DeploymentException(e);

    } catch (Throwable t) {
        if (log.isInfoEnabled()) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            t.printStackTrace(pw);
            log.info(Messages.getMessage(DeploymentErrorMsgs.INVALID_SERVICE, deploymentFileData.getName(),
                    sw.getBuffer().toString()));
        }
        PrintWriter error_ptintWriter = new PrintWriter(errorWriter);
        t.printStackTrace(error_ptintWriter);
        serviceStatus = "Error:\n" + errorWriter.toString();

        throw new DeploymentException(new Exception(t));

    } finally {
        if (serviceStatus.startsWith("Error:")) {
            axisConfig.getFaultyServices().put(deploymentFileData.getFile().getAbsolutePath(), serviceStatus);
        }
    }
}

From source file:com.flexive.war.beans.admin.main.ScriptConsoleBean.java

/**
 * Runs the given script code/*from   ww  w  .  j  av a 2s .c  om*/
 */
public void runScript() {
    if (StringUtils.isBlank(code))
        new FxFacesMsgErr("Script.err.noCodeProvided").addToContext();
    else {
        long start = System.currentTimeMillis();
        try {
            result = runScript(code, "console." + language, web);
        } catch (Throwable t) {
            final StringWriter writer = new StringWriter();
            t.printStackTrace(new PrintWriter(writer));
            final String msg = t.getCause() != null ? t.getCause().getMessage() : t.getMessage();
            result = new Formatter().format("Exception caught: %s%n%s", msg, writer.getBuffer());
        } finally {
            executionTime = System.currentTimeMillis() - start;
        }
    }
}

From source file:gtu._work.ui.SqlCreaterUI.java

private void executeBtnPreformed() {
    try {//from   ww w .  j av  a 2s . c  o m
        logArea.setText("");
        File srcFile = JCommonUtil.filePathCheck(excelFilePathText.getText(), "?", false);
        if (srcFile == null) {
            return;
        }
        if (!srcFile.getName().endsWith(".xlsx")) {
            JCommonUtil._jOptionPane_showMessageDialog_error("excel");
            return;
        }
        if (StringUtils.isBlank(sqlArea.getText())) {
            return;
        }
        File saveFile = JCommonUtil._jFileChooser_selectFileOnly_saveFile();
        if (saveFile == null) {
            JCommonUtil._jOptionPane_showMessageDialog_error("?");
            return;
        }

        String sqlText = sqlArea.getText();

        StringBuffer sb = new StringBuffer();
        Map<Integer, String> refMap = new HashMap<Integer, String>();
        Pattern sqlPattern = Pattern.compile("\\$\\{(\\w+)\\}", Pattern.MULTILINE);
        Matcher matcher = sqlPattern.matcher(sqlText);
        while (matcher.find()) {
            String val = StringUtils.trim(matcher.group(1)).toUpperCase();
            refMap.put(ExcelUtil.cellEnglishToPos(val), val);
            matcher.appendReplacement(sb, "\\$\\{" + val + "\\}");
        }
        matcher.appendTail(sb);
        appendLog(refMap.toString());

        sqlText = sb.toString();
        sqlArea.setText(sqlText);

        Configuration cfg = new Configuration();
        StringTemplateLoader stringTemplatge = new StringTemplateLoader();
        stringTemplatge.putTemplate("aaa", sqlText);
        cfg.setTemplateLoader(stringTemplatge);
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        Template temp = cfg.getTemplate("aaa");

        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(saveFile), "utf8"));

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(bis);
        Sheet sheet = xssfWorkbook.getSheetAt(0);
        for (int j = 0; j < sheet.getPhysicalNumberOfRows(); j++) {
            Row row = sheet.getRow(j);
            if (row == null) {
                continue;
            }
            Map<String, Object> root = new HashMap<String, Object>();
            for (int index : refMap.keySet()) {
                root.put(refMap.get(index), formatCellType(row.getCell(index)));
            }
            appendLog(root.toString());

            StringWriter out = new StringWriter();
            temp.process(root, out);
            out.flush();
            String writeStr = out.getBuffer().toString();
            appendLog(writeStr);

            writer.write(writeStr);
            writer.newLine();
        }
        bis.close();

        writer.flush();
        writer.close();

        JCommonUtil._jOptionPane_showMessageDialog_info("? : \n" + saveFile);
    } catch (Exception ex) {
        JCommonUtil.handleException(ex);
    }
}

From source file:com.laex.j2objc.AntDelegate.java

/**
 * Append exclude pattern to xml./* ww w  .  j  a va2 s .c o  m*/
 * 
 * @param path
 *            the path
 * @param pats
 *            the pats
 * @throws ParserConfigurationException
 *             the parser configuration exception
 * @throws SAXException
 *             the SAX exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws XPathExpressionException
 *             the x path expression exception
 * @throws CoreException
 *             the core exception
 * @throws TransformerException
 *             the transformer exception
 */
private void appendExcludePatternToXML(IFile path, String[] pats) throws ParserConfigurationException,
        SAXException, IOException, XPathExpressionException, CoreException, TransformerException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document dom = builder.parse(path.getContents());

    XPathFactory xpathfactory = XPathFactory.newInstance();
    XPath xpath = xpathfactory.newXPath();
    XPathExpression expr = xpath.compile("project/target/move/fileset");

    Node node = (Node) expr.evaluate(dom, XPathConstants.NODE);
    NodeList children = node.getChildNodes();

    // don't why the last node in the xml should be indexed by length - 2
    Node excludeCopy = children.item(children.getLength() - 2).cloneNode(true);
    for (String pattern : pats) {
        if (StringUtils.isNotEmpty(pattern.trim())) {
            Node newnode = excludeCopy.cloneNode(true);
            newnode.getAttributes().getNamedItem("name").setNodeValue(pattern);
            node.appendChild(newnode);
        }
    }

    // Setup transformers
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    StringWriter sw = new StringWriter();
    transformer.transform(new DOMSource(dom), new StreamResult(sw));
    String output = sw.getBuffer().toString();

    // save the ouput
    ByteArrayInputStream bis = new ByteArrayInputStream(output.getBytes("utf-8"));
    path.setContents(bis, 0, null);
}