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:net.sourceforge.subsonic.controller.JAXBWriter.java

public void writeResponse(HttpServletRequest request, HttpServletResponse httpResponse, Response jaxbResponse)
        throws Exception {

    String format = getStringParameter(request, "f", "xml");
    String jsonpCallback = request.getParameter("callback");
    boolean json = "json".equals(format);
    boolean jsonp = "jsonp".equals(format) && jsonpCallback != null;
    Marshaller marshaller;/*from  ww  w  .java2  s . c om*/

    if (json) {
        marshaller = createJsonMarshaller();
        httpResponse.setContentType("application/json");
    } else if (jsonp) {
        marshaller = createJsonMarshaller();
        httpResponse.setContentType("text/javascript");
    } else {
        marshaller = createXmlMarshaller();
        httpResponse.setContentType("text/xml");
    }

    httpResponse.setCharacterEncoding(StringUtil.ENCODING_UTF8);

    try {
        StringWriter writer = new StringWriter();
        if (jsonp) {
            writer.append(jsonpCallback).append('(');
        }
        marshaller.marshal(new ObjectFactory().createSubsonicResponse(jaxbResponse), writer);
        if (jsonp) {
            writer.append(");");
        }
        httpResponse.getWriter().append(writer.getBuffer());
    } catch (Exception x) {
        LOG.error("Failed to marshal JAXB", x);
        throw x;
    }
}

From source file:disko.PDFDocument.java

protected synchronized String load() {
    final StringWriter stringOutput = new StringWriter();
    PDDocument document = null;/*from  w  w w .  j a v a 2  s . c om*/
    try {
        document = PDDocument.load(ContentDownloader.getInstance().getInputStream(getUrlString()));
        title = document.getDocumentInformation().getTitle();
        PDFTextStripper stripper = new PDFTextStripper() {
            int startPage = 0;

            private int getIndex() {
                return stringOutput.getBuffer().length();
            }

            @Override
            protected void startPage(PDPage page) throws IOException {
                startPage = getIndex();
                log.debug("START PAGE " + getCurrentPageNo() + " AT " + startPage);
            }

            @Override
            protected void endPage(PDPage page) throws IOException {
                int endPage = getIndex();
                DocumentAnn ann = new DocumentAnn(startPage, endPage, PAGE_ANN);
                annotations.add(ann);
                log.debug("END PAGE " + getCurrentPageNo() + " AT " + endPage);
            }

        };
        //            stripper.setSortByPosition(false);
        //            String maxPageSetting = System.getProperty("disco.pdf.max.pages", 
        //                                             Integer.toString(Integer.MAX_VALUE));
        //            stripper.setEndPage(Integer.parseInt(maxPageSetting));
        stripper.writeText(document, stringOutput);
    } catch (Throwable t) {
        throw new RuntimeException("Unable to read resource at URL '" + url + "'", t);
    } finally {
        if (stringOutput != null) {
            try {
                stringOutput.close();
            } catch (IOException e) {
            }
        }
        if (document != null) {
            try {
                document.close();
            } catch (IOException e) {
            }
        }
    }

    String s = DU.replaceUnicodePunctuation(stringOutput.toString());
    ParagraphDetector.detectParagraphs(s, this.annotations);

    return (fullText = new WeakReference<String>(s)).get();
}

From source file:cn.com.sinosoft.util.exception.ExceptionUtils.java

/**
 * <p>//  ww  w .  j  a va 2s .  c o m
 * A way to get the entire nested stack-trace of an throwable.
 * </p>
 * 
 * <p>
 * The result of this method is highly dependent on the JDK version and
 * whether the exceptions override printStackTrace or not.
 * </p>
 * 
 * @param throwable
 *            the <code>Throwable</code> to be examined
 * @return the nested stack trace, with the root cause first
 * @since 2.0
 */
public static String getFullStackTrace(Throwable throwable) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw, true);
    Throwable[] ts = getThrowables(throwable);
    for (int i = 0; i < ts.length; i++) {
        ts[i].printStackTrace(pw);
        if (isNestedThrowable(ts[i])) {
            break;
        }
    }
    return sw.getBuffer().toString();
}

From source file:com.vmware.gemfire.tools.pulse.tests.junit.BaseServiceTest.java

/**
*
* Tests that service returns json object
*
* Test method for {@link com.vmware.gemfire.tools.pulse.internal.service.ClusterSelectedRegionService#execute(javax.servlet.http.HttpServletRequest)}.
*///from   w ww.  j ava 2s  .  co  m
@Test
public void testServerLoginLogout() {
    System.out.println("BaseServiceTest ::  ------TESTCASE BEGIN : SERVER LOGIN-LOGOUT------");
    try {
        doLogin();

        HttpUriRequest pulseupdate = RequestBuilder.get().setUri(new URI(IS_AUTHENTICATED_USER_URL)).build();
        CloseableHttpResponse response = httpclient.execute(pulseupdate);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("BaseServiceTest :: HTTP request status : " + response.getStatusLine());

            BufferedReader respReader = new BufferedReader(new InputStreamReader(entity.getContent()));
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            String sz = null;
            while ((sz = respReader.readLine()) != null) {
                pw.print(sz);
            }
            String jsonResp = sw.getBuffer().toString();
            System.out.println("BaseServiceTest :: JSON response returned : " + jsonResp);
            EntityUtils.consume(entity);

            JsonNode jsonObj = mapper.readTree(jsonResp);
            boolean isUserLoggedIn = jsonObj.get("isUserLoggedIn").booleanValue();
            Assert.assertNotNull("BaseServiceTest :: Server returned null response in 'isUserLoggedIn'",
                    isUserLoggedIn);
            Assert.assertTrue("BaseServiceTest :: User login failed for this username, password",
                    (isUserLoggedIn == true));
        } finally {
            response.close();
        }

        doLogout();
    } catch (Exception failed) {
        logException(failed);
        Assert.fail("Exception ! ");
    }
    System.out.println("BaseServiceTest ::  ------TESTCASE END : SERVER LOGIN-LOGOUT------");
}

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

/**
 * Refactorisation of the groovy upload//from  w ww .ja  va2s  .c  om
 *
 * @param code the script code
 * @return returns true if the import / running the script went ok
 */
private boolean groovyUpload(String code) {
    final String fileName = "importConsole.groovy";
    long start = System.currentTimeMillis();

    try {
        result = ScriptConsoleBean.runScript(code, fileName, false);
        return true;
    } 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());
        return false;
    } finally {
        executionTime = System.currentTimeMillis() - start;
    }
}

From source file:org.ngrinder.script.controller.SvnDavController.java

/**
 * Request Handler.//from www.j a v a2s . c  o  m
 *
 * @param request  request
 * @param response response
 * @throws ServletException occurs when servlet has a problem.
 * @throws IOException      occurs when file system has a problem.
 */
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (LOGGER.isTraceEnabled()) {
        logRequest(request);
    }
    try {
        // To make it understand Asian Language..
        request = new MyHttpServletRequestWrapper(request);
        DAVRepositoryManager repositoryManager = new DAVRepositoryManager(getDAVConfig(), request);
        ServletDAVHandler handler = DAVHandlerFactory.createHandler(repositoryManager, request, response);
        handler.execute();
    } catch (DAVException de) {
        response.setContentType(XML_CONTENT_TYPE);
        handleError(de, response);
    } catch (SVNException svne) {
        StringWriter sw = new StringWriter();
        svne.printStackTrace(new PrintWriter(sw));

        /**
         * truncate status line if it is to long
         */
        String msg = sw.getBuffer().toString();
        if (msg.length() > 128) {
            msg = msg.substring(0, 128);
        }
        SVNErrorCode errorCode = svne.getErrorMessage().getErrorCode();
        if (errorCode == SVNErrorCode.FS_NOT_DIRECTORY || errorCode == SVNErrorCode.FS_NOT_FOUND
                || errorCode == SVNErrorCode.RA_DAV_PATH_NOT_FOUND) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        } else if (errorCode == SVNErrorCode.NO_AUTH_FILE_PATH) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, msg);
        } else if (errorCode == SVNErrorCode.RA_NOT_AUTHORIZED) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, msg);
        } else {
            String errorBody = generateStandardizedErrorBody(errorCode.getCode(), null, null,
                    svne.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType(XML_CONTENT_TYPE);
            response.getWriter().print(errorBody);
        }
    } catch (Throwable th) {
        StringWriter sw = new StringWriter();
        th.printStackTrace(new PrintWriter(sw));
        String msg = sw.getBuffer().toString();
        LOGGER.debug("Error in DavSVN Controller", th);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
    } finally {
        response.flushBuffer();
    }
}

From source file:it.cnr.icar.eric.server.persistence.rdb.EmailAddressDAO.java

public void insert(@SuppressWarnings("rawtypes") List users) throws RegistryException {
    // log.info(ServerResourceBundle.getInstance().getString("message.InsertingEmailAddresss", new Object[]{new Integer(emailAddresss.size())}));
    if (users.size() == 0) {
        return;//  w  w w. j  av  a  2s.c  o  m
    }

    Statement stmt = null;

    try {
        Iterator<?> usersIter = users.iterator();
        stmt = context.getConnection().createStatement();

        while (usersIter.hasNext()) {
            UserType user = (UserType) usersIter.next();

            if (log.isDebugEnabled()) {
                try {
                    StringWriter writer = new StringWriter();
                    //                        bu.rimFac.createMarshaller()
                    bu.getJAXBContext().createMarshaller().marshal(user, writer);
                    log.debug("Inserting user: " + writer.getBuffer().toString());
                } catch (Exception e) {
                    log.debug("Failed to marshal user: ", e);
                }
            }

            String parentId = user.getId();

            List<EmailAddressType> emails = user.getEmailAddress();
            Iterator<EmailAddressType> emailsIter = emails.iterator();

            while (emailsIter.hasNext()) {
                //Log.print(Log.TRACE, 8, "\tDATABASE EVENT: storing EmailAddress " );
                Object obj = emailsIter.next();

                EmailAddressType emailAddress = (EmailAddressType) obj;

                String address = emailAddress.getAddress();

                String type = emailAddress.getType();

                if (type != null) {
                    type = "'" + type + "'";
                }

                String str = "INSERT INTO " + getTableName() + " VALUES( " + "'" + address + "', " + type + ", "
                        + "'" + parentId + "' )";
                log.trace("stmt = " + str);
                stmt.addBatch(str);
            }
        }

        if (users.size() > 0) {
            stmt.executeBatch();
        }
    } catch (SQLException e) {
        RegistryException exception = new RegistryException(e);
        throw exception;
    } finally {
        closeStatement(stmt);
    }
}

From source file:org.apache.falcon.oozie.OozieEntityBuilder.java

protected Path marshal(Cluster cluster, JAXBElement<?> jaxbElement, JAXBContext jaxbContext, Path outPath)
        throws FalconException {
    FileSystem fs = HadoopClientFactory.get().createProxiedFileSystem(outPath.toUri(),
            ClusterHelper.getConfiguration(cluster));
    verifyOozieEntityPath(fs, outPath, jaxbElement.getDeclaredType());
    try {//w  w  w.j  a v  a2  s .c  o  m
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        if (LOG.isDebugEnabled()) {
            StringWriter writer = new StringWriter();
            marshaller.marshal(jaxbElement, writer);
            LOG.debug("Writing definition to {} on cluster {}", outPath, cluster.getName());
            LOG.debug(writer.getBuffer().toString());
        }

        OutputStream out = fs.create(outPath);

        try {
            marshaller.marshal(jaxbElement, out);
        } finally {
            out.close();
        }

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

From source file:com.linuxbox.enkive.imap.message.EnkiveImapTemplateMessage.java

@Override
public long getFullContentOctets() {
    StringWriter stringWriter = new StringWriter();
    try {/*from  w  w  w.j a  v a 2 s.c o  m*/
        messageBody.process(root, stringWriter);
    } catch (TemplateException e) {
        LOGGER.error("Error producing IMAP Inbox message from template", e);
    } catch (IOException e) {
        LOGGER.error("Error producing IMAP Inbox message from template", e);
    }
    StringBuffer message = stringWriter.getBuffer();
    return headers.length() + message.length();
}

From source file:org.apereo.portal.security.xslt.XalanMessageHelperTest.java

@Test
public void testIsUserDeepMemberOf() throws Exception {
    final IXalanMessageHelper helperBean = createMock(IXalanMessageHelper.class);

    expect(helperBean.getMessage("im.done", "en_us")).andReturn("I'm Done!");

    replay(helperBean);/*w  w w  . jav  a2 s .co m*/

    XalanMessageHelper helper = new XalanMessageHelper();
    helper.setMessageHelper(helperBean);

    // set up configuration in the transformer impl
    final StringWriter resultWriter = new StringWriter();

    final InputStream xslStream = this.getClass().getResourceAsStream("messagesTest.xsl");
    final StreamSource xslSource = new StreamSource(xslStream);
    final Transformer transformer = tFactory.newTransformer(xslSource);

    transformer.setParameter("USER_LANG", "en_us");

    transformer.transform(xmlSource, new StreamResult(resultWriter));

    final String result = resultWriter.getBuffer().toString();
    logger.debug(result);

    final String expected = IOUtils.toString(this.getClass().getResourceAsStream("messagesResult.xml"));

    XMLUnit.setIgnoreWhitespace(true);
    Diff d = new Diff(expected, result);
    assertTrue("Transformation result differs from what's expected" + d, d.similar());

    verify(helperBean);
}