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.apache.axis.deployment.wsdd.WSDDDocument.java

/**
 * get the deployment as a DOM./* w ww .j a  v a  2  s.  c  o  m*/
 * Requires that the deployment member variable is not null.
 * @return
 * @throws ConfigurationException
 */
public Document getDOMDocument() throws ConfigurationException {
    StringWriter writer = new StringWriter();
    SerializationContext context = new SerializationContext(writer);
    context.setPretty(true);
    try {
        deployment.writeToContext(context);
    } catch (Exception e) {
        log.error(Messages.getMessage("exception00"), e);
    }
    try {
        writer.close();
        return XMLUtils.newDocument(new InputSource(new StringReader(writer.getBuffer().toString())));
    } catch (Exception e) {
        return null;
    }
}

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

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

    expect(helperBean.canRender("testUser", "portlet-admin")).andReturn(true);

    replay(helperBean);/*from ww w  .  j av  a2  s  .  c  o  m*/

    XalanAuthorizationHelper helper = new XalanAuthorizationHelper();
    helper.setAuthorizationHelper(helperBean);

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

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

    transformer.setParameter("USER_ID", "testUser");

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

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

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

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

    verify(helperBean);
}

From source file:net.sf.reportengine.TestDefaultReport.java

@Test
public void testTwoComponents() throws IOException {
    StringWriter testWriter = new StringWriter();
    MockReportOutput mockOutput = new MockReportOutput(testWriter);
    new ReportBuilder(mockOutput).add(new Paragraph("unit test", HorizAlign.CENTER))
            .add(new FlatTableBuilder(Scenario1.INPUT).dataColumns(Scenario1.DATA_COLUMNS).build()).build()
            .execute();/*www  . java 2  s  . co m*/

    Assert.assertEquals(EXPECTED_OUTPUT_TEST_TWO_COMPONENTS, testWriter.getBuffer().toString());
}

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

@Test
public void testFetchTargets() throws CmdLineParseException {
    FetcherConfig config = new FetcherConfig();

    StringWriter capture = new StringWriter();
    ConfigCmdLineParser parser = new ConfigCmdLineParser(this, config);
    parser.setOut(capture);//w  ww.  j  av a  2  s .  c  o  m
    String[] args = { "2.1", "froyo", "android-sdk-2.0_r1", "9" };
    parser.parse(args);

    Assert.assertThat("output should not be usage", capture.getBuffer().toString(),
            not(containsString("Usage: ")));

    List<String> targets = config.getFetchTargets();
    Assert.assertThat("config.fetchTargets", targets, notNullValue());
    Assert.assertThat("config.fetchTarget.size", targets.size(), is(4));

    Assert.assertThat("config.fetchTarget", targets, hasItem("2.1"));
    Assert.assertThat("config.fetchTarget", targets, hasItem("froyo"));
    Assert.assertThat("config.fetchTarget", targets, hasItem("android-sdk-2.0_r1"));
    Assert.assertThat("config.fetchTarget", targets, hasItem("9"));
}

From source file:com.prowidesoftware.swift.model.mx.BusinessHeader.java

/**
 * Get this header as an XML string./*from  w  w  w. j  a  v  a2 s . c o  m*/
 * Since this class contains a dual model supporting two type of headers (swift and ISO), if both
 * headers are present in the object the BusinessApplicationHeaderV01 will be used.
 * 
 * @param prefix optional prefix for namespace (empty by default)
 * @param includeXMLDeclaration true to include the XML declaration (false by default)
 * @return header serialized into XML string or null if neither header version is present
 * @since 7.8
 */
public String xml(final String prefix, boolean includeXMLDeclaration) {
    Object header = null;
    if (this.businessApplicationHeader != null) {
        header = this.businessApplicationHeader;
    } else if (this.applicationHeader != null) {
        header = this.applicationHeader;
    } else {
        return null;
    }
    try {
        JAXBContext context = JAXBContext.newInstance(header.getClass());
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        final StringWriter sw = new StringWriter();
        marshaller.marshal(_element(header), new XmlEventWriter(sw, prefix, includeXMLDeclaration, "AppHdr"));
        return sw.getBuffer().toString();

    } catch (JAXBException e) {
        log.log(Level.SEVERE, "Error writing XML:" + e + "\n for header: " + header);
    }
    return null;
}

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

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

    expect(helperBean.isChannelDeepMemberOf("fnameValue", "local.1")).andReturn(true);
    expect(helperBean.isChannelDeepMemberOf("fnameValue", "local.2")).andReturn(false);
    expect(helperBean.isUserDeepMemberOfGroupName("testUser", "Fragment Owners")).andReturn(true);

    replay(helperBean);// w  w  w  .  j a va2 s . com

    XalanGroupMembershipHelper helper = new XalanGroupMembershipHelper();
    helper.setGroupMembershipHelper(helperBean);

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

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

    transformer.setParameter("USER_ID", "testUser");

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

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

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

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

    verify(helperBean);
}

From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java

public static String prettyPrintDOMWithEncoding(Document doc, String defaultEncoding) {
    StringWriter writer = new StringWriter();
    prettyPrintDOMWithEncoding(doc, defaultEncoding, writer);
    return writer.getBuffer().toString();
}

From source file:org.apache.asterix.test.common.TestExecutor.java

private static String getProcessOutput(Process p) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Future<Integer> future = Executors.newSingleThreadExecutor()
            .submit(() -> IOUtils.copy(p.getInputStream(), new OutputStream() {
                @Override/*  ww w  .  ja  va2s  . c om*/
                public void write(int b) throws IOException {
                    baos.write(b);
                    System.out.write(b);
                }

                @Override
                public void flush() throws IOException {
                    baos.flush();
                    System.out.flush();
                }

                @Override
                public void close() throws IOException {
                    baos.close();
                    System.out.close();
                }
            }));
    p.waitFor();
    future.get();
    ByteArrayInputStream bisIn = new ByteArrayInputStream(baos.toByteArray());
    StringWriter writerIn = new StringWriter();
    IOUtils.copy(bisIn, writerIn, StandardCharsets.UTF_8);
    StringWriter writerErr = new StringWriter();
    IOUtils.copy(p.getErrorStream(), writerErr, StandardCharsets.UTF_8);

    StringBuffer stdOut = writerIn.getBuffer();
    if (writerErr.getBuffer().length() > 0) {
        StringBuilder sbErr = new StringBuilder();
        sbErr.append("script execution failed - error message:\n"
                + "-------------------------------------------\n" + "stdout: ").append(stdOut)
                .append("\nstderr: ").append(writerErr.getBuffer())
                .append("-------------------------------------------");
        LOGGER.info(sbErr.toString());
        throw new Exception(sbErr.toString());
    }
    return stdOut.toString();
}

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

/**
 * Request Handler./* ww w.  j  a v  a  2  s .  c om*/
 * 
 * @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 {
        final String head = DAVPathUtil.head(request.getPathInfo());
        final User currentUser = userContext.getCurrentUser();
        // check the security. If the other user tries to the other user's
        // repo, deny it.
        if (!StringUtils.equals(currentUser.getUserId(), head)) {
            SecurityContextHolder.getContext().setAuthentication(null);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                    head + " is not accessible by " + currentUser.getUserId());
            return;
        }
        // To make it understand Asian Language..
        request = new MyHttpServletRequestWrapper(request);
        DAVRepositoryManager repositoryManager = new DAVRepositoryManager(getDAVConfig(), request);
        ServletDAVHandler handler = DAVHandlerExFactory.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:net.erdfelt.android.sdkfido.configer.ConfigCmdLineParserTest.java

@Test
public void testInvalidOption() {
    FetcherConfig config = new FetcherConfig();

    StringWriter capture = new StringWriter();
    ConfigCmdLineParser parser = new ConfigCmdLineParser(this, config);
    parser.setOut(capture);//from w  ww. j a  v  a  2 s.com
    String[] args = { "--bogus-thing" };
    try {
        parser.parse(args);
        Assert.fail("Expected " + CmdLineParseException.class.getName() + "\n" + capture.getBuffer());
    } catch (CmdLineParseException e) {
        parser.usage(e);
        assertHasThrowable(capture, CmdLineParseException.class);
        assertContains(capture, "Invalid Option: --bogus-thing");
        assertContains(capture, "Usage: ");
    }
}