org.apache.commons.io.output.StringBuilderWriter Java Examples

The following examples show how to use org.apache.commons.io.output.StringBuilderWriter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ValueHolderReplacementVisitor.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public void visitEnd() {
  try {
    accept(inner);
    super.visitEnd();
  } catch(Exception e){
    Textifier t = new Textifier();
    accept(new TraceMethodVisitor(t));
    StringBuilderWriter sw = new StringBuilderWriter();
    PrintWriter pw = new PrintWriter(sw);
    t.print(pw);
    pw.flush();
    String bytecode = sw.getBuilder().toString();
    logger.error(String.format("Failure while rendering method %s, %s, %s.  ByteCode:\n %s", name, desc, signature, bytecode), e);
    throw new RuntimeException(String.format("Failure while rendering method %s, %s, %s.  ByteCode:\n %s", name, desc, signature, bytecode), e);
  }
}
 
Example #2
Source File: XsltRendererTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
private String renderSimpleStyleSheet(String src) throws IOException {
    String template = "<?xml version=\"1.0\"?>";
    template +=
            "<xsl:stylesheet version=\"1.0\" xmlns=\"http://www.w3.org/1999/xhtml\" "
                    + "xmlns:html=\"http://www.w3.org/1999/xhtml\" "
                    + "xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">";
    template += "<xsl:output method=\"xml\" omit-xml-declaration=\"yes\"/>";
    template += "<xsl:template match=\"//html:body\">";
    template += "<xsl:copy-of select=\".\"/>";
    template += "</xsl:template>";
    template += "<xsl:template match=\"text()\"/>";
    template += "</xsl:stylesheet>";
    StringBuilderWriter out = new StringBuilderWriter();
    XsltRenderer tested = new XsltRenderer(template);
    tested.render(null, src, out);
    return out.toString();
}
 
Example #3
Source File: XsltRendererTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
private String renderExtensionStyleSheet(String src) throws IOException {
    String template = "<?xml version=\"1.0\"?>";
    template +=
            "<xsl:stylesheet version=\"1.0\" xmlns=\"http://www.w3.org/1999/xhtml\" "
                    + "xmlns:html=\"http://www.w3.org/1999/xhtml\" "
                    + "xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">";
    template += "<xsl:output method=\"xml\" omit-xml-declaration=\"yes\"/>";
    template +=
            "<xsl:template match=\"/\"  xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:rt=\"http://xml.apache.org/xalan/java/java.lang.Runtime\">";

    template += "<xsl:variable name=\"rtObj\" select=\"rt:getRuntime()\"/>";
    template += "<xsl:variable name=\"process\" select=\"rt:totalMemory($rtObj)\"/>";
    template += "Process: <xsl:value-of select=\"$process\"/>\n";

    template += "</xsl:template>";

    template += "</xsl:stylesheet>";
    StringBuilderWriter out = new StringBuilderWriter();
    XsltRenderer tested = new XsltRenderer(template);
    tested.render(null, src, out);
    return out.toString();
}
 
Example #4
Source File: ResourceFixupRendererTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
public void testRenderBlock1() throws IOException {
    String baseUrl = "http://backend/context";
    String requestUrl = "path/page.html";
    String visibleBaseUrl = baseUrl;
    final String input = "some html";

    UrlRewriter urlRewriter = Mockito.mock(UrlRewriter.class);
    Mockito.when(urlRewriter.rewriteHtml(input, requestUrl, baseUrl, visibleBaseUrl, false)).thenReturn(
            "url rewritten html");

    Writer out = new StringBuilderWriter();
    ResourceFixupRenderer tested =
            new ResourceFixupRenderer(baseUrl, requestUrl, urlRewriter, visibleBaseUrl, false);
    tested.render(null, input, out);

    Mockito.verify(urlRewriter, Mockito.times(1)).rewriteHtml(input, requestUrl, baseUrl, visibleBaseUrl, false);
    assertEquals("url rewritten html", out.toString());
}
 
Example #5
Source File: Driver.java    From esigate with Apache License 2.0 6 votes vote down vote up
/**
 * Performs rendering (apply a render list) on an http response body (as a String).
 * 
 * @param pageUrl
 *            The remove url from which the body was retrieved.
 * @param originalRequest
 *            The request received by esigate.
 * @param response
 *            The Http Reponse.
 * @param body
 *            The body of the Http Response which will be rendered.
 * @param renderers
 *            list of renderers to apply.
 * @return The rendered response body.
 * @throws HttpErrorPage
 * @throws IOException
 */
private String performRendering(String pageUrl, DriverRequest originalRequest, CloseableHttpResponse response,
        String body, Renderer[] renderers) throws IOException, HttpErrorPage {
    // Start rendering
    RenderEvent renderEvent = new RenderEvent(pageUrl, originalRequest, response);
    // Create renderer list from parameters.
    renderEvent.getRenderers().addAll(Arrays.asList(renderers));

    String currentBody = body;

    this.eventManager.fire(EventManager.EVENT_RENDER_PRE, renderEvent);
    for (Renderer renderer : renderEvent.getRenderers()) {
        StringBuilderWriter stringWriter = new StringBuilderWriter(Parameters.DEFAULT_BUFFER_SIZE);
        renderer.render(originalRequest, currentBody, stringWriter);
        stringWriter.close();
        currentBody = stringWriter.toString();
    }
    this.eventManager.fire(EventManager.EVENT_RENDER_POST, renderEvent);

    return currentBody;
}
 
Example #6
Source File: SpinRendererTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static String toRDF(StatementCollector stmts) throws RDFHandlerException {
	WriterConfig config = new WriterConfig();
	config.set(BasicWriterSettings.PRETTY_PRINT, false);
	StringBuilderWriter writer = new StringBuilderWriter();
	final RDFWriter rdfWriter = Rio.createWriter(RDFFormat.TURTLE, writer);
	rdfWriter.setWriterConfig(config);

	rdfWriter.startRDF();
	for (Map.Entry<String, String> entry : stmts.getNamespaces().entrySet()) {
		rdfWriter.handleNamespace(entry.getKey(), entry.getValue());
	}
	for (final Statement st : stmts.getStatements()) {
		rdfWriter.handleStatement(st);
	}
	rdfWriter.endRDF();

	writer.close();
	return writer.toString();
}
 
Example #7
Source File: AppResource.java    From app-runner with MIT License 6 votes vote down vote up
@POST /* Maybe should be PUT, but too many hooks only use POST */
@Produces({MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON})
@Path("/{name}/deploy")
@Description(value = "Deploys an app", details = "Deploys the app by fetching the latest changes from git, building it, " +
    "starting it, polling for successful startup by making GET requests to /{name}/, and if it returns any HTTP response " +
    "it shuts down the old version of the app. If any steps before that fail, the old version of the app will continue serving " +
    "requests.")
@ApiResponse(code = "200", message = "Returns 200 if the command was received successfully. Whether the build " +
    "actually succeeds or fails is ignored. Returns streamed plain text of the build log and console startup, unless the Accept" +
    " header includes 'application/json'.")
public Response deploy(@Context UriInfo uriInfo, @Description(value = "The type of response desired, e.g. application/json or text/plain", example = "application/json") @HeaderParam("Accept") String accept,
                       @Required @Description(value="The name of the app", example = "app-runner-home") @PathParam("name") String name) throws IOException {
    StreamingOutput stream = new UpdateStreamer(name);
    if (MediaType.APPLICATION_JSON.equals(accept)) {
        StringBuilderWriter output = new StringBuilderWriter();
        try (WriterOutputStream writer = new WriterOutputStream(output)) {
            stream.write(writer);
            return app(uriInfo, name);
        }
    } else {
        return Response.ok(stream).type("text/plain;charset=utf-8").build();
    }
}
 
Example #8
Source File: SystemInfo.java    From app-runner with MIT License 6 votes vote down vote up
private static List<String> getPublicKeys() throws Exception {
    return new JschConfigSessionFactory() {
        @Override
        protected void configure(OpenSshConfig.Host hc, Session session) {
        }
        List<String> getPublicKeys() throws Exception {
            JSch jSch = createDefaultJSch(FS.DETECTED);
            List<String> keys = new ArrayList<>();
            for (Object o : jSch.getIdentityRepository().getIdentities()) {
                Identity i = (Identity) o;
                KeyPair keyPair = KeyPair.load(jSch, i.getName(), null);
                StringBuilder sb = new StringBuilder();
                try (StringBuilderWriter sbw = new StringBuilderWriter(sb);
                     OutputStream os = new WriterOutputStream(sbw, "UTF-8")) {
                    keyPair.writePublicKey(os, keyPair.getPublicKeyComment());
                } finally {
                    keyPair.dispose();
                }
                keys.add(sb.toString().trim());
            }
            return keys;
        }
    }.getPublicKeys();
}
 
Example #9
Source File: ProcessStarterTest.java    From app-runner with MIT License 6 votes vote down vote up
static void startAndStop(int attempt, String appName, AppRunner runner, int port, StringBuilderWriter buildLog, StringBuilderWriter consoleLog, Matcher<String> getResponseMatcher, Matcher<String> buildLogMatcher) throws Exception {
    try {
        try (Waiter startupWaiter = Waiter.waitForApp(appName, port)) {
            runner.start(
                new OutputToWriterBridge(buildLog),
                new OutputToWriterBridge(consoleLog),
                TestConfig.testEnvVars(port, appName),
                startupWaiter);
        }
        try {
            ContentResponse resp = httpClient.GET("http://localhost:" + port + "/" + appName + "/");
            assertThat(resp.getStatus(), is(200));
            assertThat(resp.getContentAsString(), getResponseMatcher);
            assertThat(buildLog.toString(), buildLogMatcher);
        } finally {
            runner.shutdown();
        }
    } catch (Exception e) {
        clearlyShowError(attempt, e, buildLog, consoleLog);
    }
}
 
Example #10
Source File: AggregateRendererTest.java    From esigate with Apache License 2.0 5 votes vote down vote up
public void testIncludeTemplate() throws IOException, HttpErrorPage {
    String page =
            "content <!--$includetemplate$mock$/testTemplateParams$mytemplate$--> some text "
                    + "<!--$beginput$param1$-->Replacement<!--$endput$-->"
                    + "some other text<!--$endincludetemplate$--> end";
    StringBuilderWriter out = new StringBuilderWriter();
    tested.render(request, page, out);
    assertEquals("content some text Replacement goes here end", out.toString());
}
 
Example #11
Source File: XpathRendererTest.java    From esigate with Apache License 2.0 5 votes vote down vote up
/**
 * Tests xpath expression evaluation for a html 5 document.
 * 
 * @throws Exception
 */
public void testXpathHtml5() throws Exception {
    String src =
            "<!doctype html>\n" + "<html lang=\"fr\">\n" + "<head>\n" + "  <meta charset=\"utf-8\">\n"
                    + "  <title>The title</title>\n" + "</head>\n" + "<body>The body</body>" + "</html>";
    StringBuilderWriter out = new StringBuilderWriter();
    XpathRenderer tested = new XpathRenderer("/html:html/html:body");
    tested.render(null, src, out);
    assertEquals("<body>The body</body>", out.toString());
}
 
Example #12
Source File: AbstractElementTest.java    From esigate with Apache License 2.0 5 votes vote down vote up
protected String render(String page) throws HttpErrorPage, IOException {
    IncomingRequest incomingRequest = requestBuilder.build();
    DriverRequest request = new DriverRequest(incomingRequest, provider, page);
    StringBuilderWriter out = new StringBuilderWriter();
    tested.render(request, page, out);
    return out.toString();
}
 
Example #13
Source File: TemplateRendererTest.java    From esigate with Apache License 2.0 5 votes vote down vote up
public void testRenderTemplateNull2() throws IOException, HttpErrorPage {
    HashMap<String, String> params = new HashMap<>();
    params.put("key", "'value'");
    params.put("some other key", "'another value'");
    StringBuilderWriter out = new StringBuilderWriter();

    TemplateRenderer tested = new TemplateRenderer(null, params, null);
    tested.render(null, null, out);

    assertFalse(out.toString().contains("key"));
    assertTrue(out.toString().contains("'value'"));
    assertFalse(out.toString().contains("some other key"));
    assertTrue(out.toString().contains("'another value'"));
}
 
Example #14
Source File: TemplateRendererTest.java    From esigate with Apache License 2.0 5 votes vote down vote up
public void testRenderTemplate1() throws IOException, HttpErrorPage {
    final String input = "some <!--$beginparam$key$-->some hidden text goes here<!--$endparam$key$--> printed";
    HashMap<String, String> params = new HashMap<>();
    params.put("key", "'value'");
    params.put("some other key", "'another value'");
    StringBuilderWriter out = new StringBuilderWriter();
    TemplateRenderer tested = new TemplateRenderer(null, params, null);
    tested.render(null, input, out);

    assertFalse(out.toString().contains("key"));
    assertTrue(out.toString().contains("'value'"));
    assertFalse(out.toString().contains("some other key"));

    assertEquals("some 'value' printed", out.toString());
}
 
Example #15
Source File: TemplateRendererTest.java    From esigate with Apache License 2.0 5 votes vote down vote up
public void testRenderTemplateWithSimilarParamNames() throws IOException, HttpErrorPage {
    final String expectedOutput =
            "some <!--$beginparam$key1$-->" + "some hidden text goes here" + "<!--$endparam$key1$--> printed";
    HashMap<String, String> params = new HashMap<>();
    params.put("key", "Should not work");
    StringBuilderWriter out = new StringBuilderWriter();
    TemplateRenderer tested = new TemplateRenderer(null, params, null);
    tested.render(null, expectedOutput, out);

    assertFalse(out.toString().contains("Should not be used as replacement"));
}
 
Example #16
Source File: TemplateRendererTest.java    From esigate with Apache License 2.0 5 votes vote down vote up
public void testRenderTemplate2() throws IOException, HttpErrorPage {
    final String expectedOutput =
            "abc some<!--$begintemplate$A$-->" + "some text goes here" + "<!--$endtemplate$A$--> cdf hello";
    StringBuilderWriter out = new StringBuilderWriter();
    TemplateRenderer tested = new TemplateRenderer("A", null, null);
    tested.render(null, expectedOutput, out);
    assertEquals("some text goes here", out.toString());
}
 
Example #17
Source File: BlockRendererTest.java    From esigate with Apache License 2.0 5 votes vote down vote up
public void testUnknownTag() throws IOException, HttpErrorPage {
    final String input = "abc some<!--$hello$world$-->some text goes here";
    Writer out = new StringBuilderWriter();
    BlockRenderer tested = new BlockRenderer(null, null);
    tested.render(null, input, out);
    // input should remain unchanged
    assertEquals(input, out.toString());
}
 
Example #18
Source File: AggregateRendererTest.java    From esigate with Apache License 2.0 5 votes vote down vote up
public void testIncludeTemplateNested() throws IOException, HttpErrorPage {
    String page =
            "content " + "<!--$includetemplate$mock$/testNestedTemplate$myblock$--> some text "
                    + "<!--$endincludetemplate$-->" + " end";
    StringBuilderWriter out = new StringBuilderWriter();
    tested.render(request, page, out);
    assertEquals("content  nested Test include /nested  end", out.toString());
}
 
Example #19
Source File: XpathRendererTest.java    From esigate with Apache License 2.0 5 votes vote down vote up
/**
 * Tests xpath expression evaluation for an xhtml document.
 * 
 * @throws Exception
 */
public void testXpathXhtml() throws Exception {
    String src =
            "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" "
                    + "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"
                    + "<html xmlns=\"http://www.w3.org/1999/xhtml\">"
                    + "<head><title>The header</title></head><body>The body<br/><b></b></body></html>";
    StringBuilderWriter out = new StringBuilderWriter();
    XpathRenderer tested = new XpathRenderer("//html:body");
    tested.render(null, src, out);
    assertEquals("<body>The body<br /><b></b></body>", out.toString());
}
 
Example #20
Source File: AggregateRendererTest.java    From esigate with Apache License 2.0 5 votes vote down vote up
public void testNestedTags() throws IOException, HttpErrorPage {
    String page =
            "content <!--$includetemplate$mock$/testTemplateParams$mytemplate$--> some text "
                    + "<!--$beginput$param1$-->aaa "
                    + "<!--$includeblock$mock$/testInclude$--> some text <!--$endincludeblock$-->"
                    + " bbb<!--$endput$-->" + "some other text<!--$endincludetemplate$--> end";
    StringBuilderWriter out = new StringBuilderWriter();
    tested.render(request, page, out);
    assertEquals("content some text aaa Test include bbb goes here end", out.toString());

}
 
Example #21
Source File: Bug101ConnectionReleaseTest.java    From esigate with Apache License 2.0 5 votes vote down vote up
private void render(Driver driver, String page) throws IOException {
    StringBuilderWriter writer = new StringBuilderWriter();
    IncomingRequest httpRequest = TestUtils.createIncomingRequest().build();
    try {
        CloseableHttpResponse response =
                driver.render("/esigate-app-aggregated1/" + page, httpRequest, new BlockRenderer(null,
                        "/esigate-app-aggregated1/" + page));
        writer.append(HttpResponseUtils.toString(response));
        writer.close();
    } catch (HttpErrorPage e) {
        LOG.info(page + " -> " + e.getHttpResponse().getStatusLine().getStatusCode());
    }
}
 
Example #22
Source File: Runner.java    From JHazm with MIT License 5 votes vote down vote up
private static void showHelp(Options options) {
    HelpFormatter formatter = new HelpFormatter();
    final StringBuilder helpBuilder = new StringBuilder().append('\n');
    helpBuilder.append("Welcome to JHazm.").append('\n');
    PrintWriter pw = new PrintWriter(new StringBuilderWriter(helpBuilder));
    formatter.printHelp(pw, 80, "java -jar jhazm.jar", null,
            options, 0, 0, "Thank you", false);
    helpBuilder.append("Required options for stemmer: --i or --t, --o").append('\n');
    System.err.println(helpBuilder);
    System.exit(0);
}
 
Example #23
Source File: FailureUrlService.java    From fess with Apache License 2.0 5 votes vote down vote up
private String getStackTrace(final Throwable t) {
    final SystemHelper systemHelper = ComponentUtil.getSystemHelper();
    final StringBuilderWriter sw = new StringBuilderWriter();
    final PrintWriter pw = new PrintWriter(sw, true);
    t.printStackTrace(pw);
    return systemHelper.abbreviateLongText(sw.toString());
}
 
Example #24
Source File: JavaXToWriterUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenUsingCommonsIO_whenConvertingByteArrayIntoWriter_thenCorrect() throws IOException {
    final byte[] initialArray = "With Commons IO".getBytes();
    final Writer targetWriter = new StringBuilderWriter(new StringBuilder(new String(initialArray)));

    targetWriter.close();

    assertEquals("With Commons IO", targetWriter.toString());
}
 
Example #25
Source File: RestExceptionMapper.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the full stack trace for the given exception and returns it as a
 * string.
 * @param data
 */
private String getStackTrace(AbstractRestException data) {
    StringBuilderWriter writer = new StringBuilderWriter();
    try {
        data.printStackTrace(new PrintWriter(writer));
        return writer.getBuilder().toString();
    } finally {
        writer.close();
    }
}
 
Example #26
Source File: XContentBuilder.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 */
public XContentBuilder() {
    try {
        writer = new StringBuilderWriter();
        json = jsonFactory.createGenerator(writer);
    } catch (IOException e) {
        // Will never happen!
        throw new RuntimeException(e);
    }
}
 
Example #27
Source File: RestExceptionMapper.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the full stack trace for the given exception and returns it as a
 * string.
 * @param data
 */
private String getStackTrace(AbstractEngineException data) {
    try (StringBuilderWriter writer = new StringBuilderWriter()) {
        data.printStackTrace(new PrintWriter(writer));
        return writer.getBuilder().toString();
    }
}
 
Example #28
Source File: RestExceptionMapper.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the full stack trace for the given exception and returns it as a
 * string.
 * @param data
 */
private String getStackTrace(AbstractEngineException data) {
    try (StringBuilderWriter writer = new StringBuilderWriter()) {
        data.printStackTrace(new PrintWriter(writer));
        return writer.getBuilder().toString();
    }
}
 
Example #29
Source File: ErrorMessagePanel.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
public ErrorMessagePanel(String id, String msg, Throwable err) {
	super(id);

	log.error(msg, err);
	add(new Label("msg", msg));
	StringBuilderWriter sw = new StringBuilderWriter();
	err.printStackTrace(new PrintWriter(sw));
	add(new Label("err", sw.toString()));
}
 
Example #30
Source File: ServerErrorMapper.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the full stack trace for the given exception and returns it as a
 * string.
 * @param data
 */
private String getStackTrace(ServerError data) {
    try (StringBuilderWriter writer = new StringBuilderWriter()) {
        data.printStackTrace(new PrintWriter(writer));
        return writer.getBuilder().toString();
    }
}