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

The following examples show how to use org.apache.commons.io.output.StringBuilderWriter. These examples are extracted from open source projects. 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 Project: Bats   Source File: ValueHolderReplacementVisitor.java    License: 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
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 3
Source Project: app-runner   Source File: AppResource.java    License: 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 4
Source Project: app-runner   Source File: SystemInfo.java    License: 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 5
Source Project: app-runner   Source File: ProcessStarterTest.java    License: 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 6
Source Project: esigate   Source File: Driver.java    License: 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 7
Source Project: esigate   Source File: XsltRendererTest.java    License: 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 8
Source Project: esigate   Source File: XsltRendererTest.java    License: 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 9
Source Project: esigate   Source File: ResourceFixupRendererTest.java    License: 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 10
public String writeToString(File docFile) throws IOException, Docx4JException {
	WordprocessingMLPackage wmlPackage = WordprocessingMLPackage.load(docFile);
	StringBuilderWriter output = new StringBuilderWriter();
	try {
		this.writeToWriter(wmlPackage, output);
	} finally {
		IOUtils.closeQuietly(output);
	}
	return output.toString();
}
 
Example 11
public String extract(File inputfile) throws Exception {
	WordprocessingMLPackage wmlPackage = WordprocessingMLPackage.load(inputfile);
	StringBuilderWriter output = new StringBuilderWriter();
	try {
		this.extract(wmlPackage, output);
	} finally {
		IOUtils.closeQuietly(output);
	}
	return output.toString();
}
 
Example 12
public String extract(WordprocessingMLPackage wmlPackage) throws Exception {
	StringBuilderWriter output = new StringBuilderWriter(); 
	try {
		this.extract(wmlPackage, output);
	} finally {
		IOUtils.closeQuietly(output);
	}
	return output.toString();
}
 
Example 13
Source Project: app-runner   Source File: ProcessStarterTest.java    License: MIT License 5 votes vote down vote up
static void clearlyShowError(int attempt, Exception e, StringBuilderWriter buildLog, StringBuilderWriter consoleLog) throws Exception {
    System.out.println("Failure on attempt " + attempt);
    System.out.println("Build log");
    System.out.println(buildLog);
    System.out.println();
    System.out.println("Console log");
    System.out.println(consoleLog);
    throw e;
}
 
Example 14
/**
 * Gets the full stack trace for the given exception and returns it as a
 * string.
 * @param data
 */
private String getStackTrace(ApiValidationException data) {
    try (StringBuilderWriter writer = new StringBuilderWriter()) {
        data.printStackTrace(new PrintWriter(writer));
        return writer.getBuilder().toString();
    }
}
 
Example 15
Source Project: apicurio-studio   Source File: ServerErrorMapper.java    License: 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();
    }
}
 
Example 16
/**
 * Gets the full stack trace for the given exception and returns it as a
 * string.
 * @param data
 */
private String getStackTrace(NullPointerException data) {
    try (StringBuilderWriter writer = new StringBuilderWriter()) {
        data.printStackTrace(new PrintWriter(writer));
        return writer.getBuilder().toString();
    }
}
 
Example 17
Source Project: template-compiler   Source File: GeneralUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Formats the {@code node} as a string using the pretty printer.
 */
public static String jsonPretty(JsonNode node) throws IOException {
  StringBuilder buf = new StringBuilder();
  JsonGenerator gen = JSON_FACTORY.createGenerator(new StringBuilderWriter(buf));
  gen.useDefaultPrettyPrinter();
  gen.setCodec(JsonUtils.getMapper());
  gen.writeTree(node);
  return buf.toString();
}
 
Example 18
Source Project: Zom-Android-XMPP   Source File: Debug.java    License: GNU General Public License v3.0 5 votes vote down vote up
static public void wrapExceptions(Runnable runnable) {
    try {
        runnable.run();
    } catch (Throwable t) {
        StringBuilderWriter writer = new StringBuilderWriter();
        PrintWriter pw = new PrintWriter(writer, true);
        t.printStackTrace(pw);
        writer.flush();
        throw new IllegalStateException("service throwable: " + writer.getBuilder().toString());
    }
}
 
Example 19
Source Project: openmeetings   Source File: ErrorMessagePanel.java    License: 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 20
Source Project: zjsonpatch   Source File: AbstractTest.java    License: Apache License 2.0 5 votes vote down vote up
private String errorMessage(String header, Exception e) throws JsonProcessingException {
    StringBuilder res =
            new StringBuilder()
                    .append(header)
                    .append("\nFull test case (in file ")
                    .append(p.getSourceFile())
                    .append("):\n")
                    .append(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(p.getNode()));
    if (e != null) {
        res.append("\nFull error: ");
        e.printStackTrace(new PrintWriter(new StringBuilderWriter(res)));
    }
    return res.toString();
}
 
Example 21
Source Project: esigate   Source File: HttpErrorPage.java    License: Apache License 2.0 5 votes vote down vote up
private static HttpEntity toMemoryEntity(Exception exception) {
    StringBuilderWriter out = new StringBuilderWriter(Parameters.DEFAULT_BUFFER_SIZE);
    PrintWriter pw = new PrintWriter(out);
    exception.printStackTrace(pw);
    String content = out.toString();
    try {
        return toMemoryEntity(content);
    } finally {
        pw.close();
    }
}
 
Example 22
Source Project: esigate   Source File: AbstractElementTest.java    License: 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 23
Source Project: esigate   Source File: FutureAppendableAdapterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBasic() throws IOException, HttpErrorPage {

    StringBuilderWriter sw = new StringBuilderWriter();

    FutureAppendableAdapter adapter = new FutureAppendableAdapter(sw);

    adapter.enqueueAppend(new CharSequenceFuture("test1"));
    adapter.enqueueAppend(new CharSequenceFuture("test2"));
    adapter.enqueueAppend(new CharSequenceFuture("test3"));
    adapter.enqueueAppend(new CharSequenceFuture("test4"));

    adapter.performAppends();
    Assert.assertEquals("test1test2test3test4", sw.toString());
}
 
Example 24
Source Project: esigate   Source File: ParserTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testParse() throws IOException, HttpErrorPage {
    String page =
            "begin " + "<test:simple name='ignored'> this text will be ignored </test:simple>"
                    + "<test:body>this text should be {request} </test:body>" + "<test:unknown name='value' />"
                    + "<test:simple name='also ignored'/>" + " end";
    StringBuilderWriter out = new StringBuilderWriter();

    tested.parse(page, out);
    assertEquals("begin this text should be updated <test:unknown name='value' /> end", out.toString());
}
 
Example 25
Source Project: esigate   Source File: XpathRendererTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests xpath expression evaluation for an html document.
 * 
 * @throws Exception
 */
public void testXpathHtml() throws Exception {
    String src = "<html><title>The header</title><body>The body<br></body></html>";
    StringBuilderWriter out = new StringBuilderWriter();
    XpathRenderer tested = new XpathRenderer("/html:html/html:body");
    tested.render(null, src, out);
    assertEquals("<body>The body<br /></body>", out.toString());
}
 
Example 26
Source Project: esigate   Source File: XpathRendererTest.java    License: 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 27
Source Project: esigate   Source File: XpathRendererTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests xpath expression targetting an attribute.
 * 
 * @throws Exception
 */
public void testXpathAttribute() 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 class=\"test\">The body<br/><b></b></body>" + "</html>";
    StringBuilderWriter out = new StringBuilderWriter();
    XpathRenderer tested = new XpathRenderer("//html:body/@class");
    tested.render(null, src, out);
    assertEquals("test", out.toString());
}
 
Example 28
Source Project: esigate   Source File: XpathRendererTest.java    License: 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 29
Source Project: esigate   Source File: AbstractElementTest.java    License: 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 30
Source Project: esigate   Source File: TemplateRendererTest.java    License: 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'"));
}