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:edu.jhu.pha.vospace.storage.SwiftStorageManager.java

public static String generateRandomCredentials(final String username) {
    return DbPoolServlet.goSql("Generate random credentials",
            "select username, apikey from storage_users_pool where user_id IS NULL limit 1;",
            new SqlWorker<String>() {
                @Override//from   w w w  .  j  a v a  2  s  .  c  o  m
                public String go(Connection conn, PreparedStatement stmt) throws SQLException {
                    ResultSet rs = stmt.executeQuery();
                    if (rs.next()) {
                        String user = rs.getString("username");
                        String password = rs.getString("apikey");
                        PreparedStatement prep = conn.prepareStatement(
                                "update storage_users_pool SET user_id = (select user_id from user_identities where identity = ?) where username = ?");
                        prep.setString(1, username);
                        prep.setString(2, user);
                        prep.execute();

                        logger.debug(username + " " + user);

                        StringWriter writer = new StringWriter();
                        JsonFactory f = new JsonFactory();
                        try {
                            JsonGenerator g = f.createJsonGenerator(writer);

                            g.writeStartObject();
                            g.writeStringField("username", user);
                            g.writeStringField("apikey", password);
                            g.writeEndObject();

                            g.close(); // important: will force flushing of output, close underlying output stream

                            return writer.getBuffer().toString();
                        } catch (JsonGenerationException ex) {
                            throw new InternalServerErrorException(
                                    "Error generating user storage credentials. " + ex.getMessage());
                        } catch (IOException e) {
                            throw new InternalServerErrorException(
                                    "Error generating user storage credentials. " + e.getMessage());
                        }

                    } else
                        throw new PermissionDeniedException("The user does not exist.");
                }
            });

}

From source file:io.marto.aem.utils.freemarker.FreemarkerTemplateFactory.java

/**
 * Same as {@link #render(String, Object, Writer)} but instead returns a StringBuffer of the rendered result instead of writing it to a writer.
 *
 * @param templatePath  the template to render (view)
 * @param model         the model/*from  w  ww .j a  va 2s  .c o m*/
 * @return a StringBuffer that contains the rendered template.
 *
 * @throws TemplateException  on template error
 * @throws IOException        on any other write error
 */
public StringBuffer renderToStringBuffer(String templatePath, Object model)
        throws TemplateException, IOException {
    final StringWriter writer = new StringWriter();
    render(templatePath, model, writer);
    return writer.getBuffer();
}

From source file:br.com.danielferber.ilogtoys.dados.DataSinkStringBuilder.java

@Override
public void consumeData(IloOplModel oplModel) throws IOException {
    StringWriter sw = new StringWriter();
    OutputStream os = new WriterOutputStream(sw);
    super.exportarStream(oplModel, os);
    stringBuilder.append(sw.getBuffer());
}

From source file:Main.java

@Override
public void start(Stage primaryStage) {
    WebEngine webEngine = new WebEngine();
    webEngine.getLoadWorker().stateProperty().addListener((obs, oldValue, newValue) -> {
        System.out.println(newValue);
        if (newValue == State.SUCCEEDED) {
            System.out.println("finished loading");
            try {
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                StringWriter stringWriter = new StringWriter();
                transformer.transform(new DOMSource(webEngine.getDocument()), new StreamResult(stringWriter));
                String xml = stringWriter.getBuffer().toString();
                System.out.println(xml);
            } catch (Exception e) {
                e.printStackTrace();/*  www.j av  a 2  s  . co m*/
            }

        }
    }); // addListener()

    // begin loading...
    webEngine.load("http://www.java2s.com");

    Group root = new Group();
    Scene scene = new Scene(root, 300, 250);

    primaryStage.setScene(scene);
    primaryStage.show();
}

From source file:com.openkm.servlet.HtmlPreviewServlet.java

/**
 * /* ww  w  .jav a2  s  .  co m*/
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doGet({}, {})", request, response);
    String uuid = WebUtils.getString(request, "uuid");
    InputStream fis = null;

    try {
        fis = OKMDocument.getInstance().getContent(null, uuid, false);
        StringWriter writer = new StringWriter();
        IOUtils.copy(fis, writer, "UTF-8");
        String content = writer.getBuffer().toString();

        ServletContext sc = getServletContext();
        sc.setAttribute("content", content);
        sc.getRequestDispatcher("/html_preview.jsp").forward(request, response);
    } catch (PathNotFoundException e) {
        sendErrorRedirect(request, response, e);
    } catch (AccessDeniedException e) {
        sendErrorRedirect(request, response, e);
    } catch (RepositoryException e) {
        sendErrorRedirect(request, response, e);
    } catch (DatabaseException e) {
        sendErrorRedirect(request, response, e);
    } finally {
        IOUtils.closeQuietly(fis);
    }
}

From source file:com.enonic.cms.core.content.contentdata.custom.support.XmlDataEntryParser.java

private String elementToString(final Element xmlRootNode) {
    final StringWriter sw = new StringWriter();
    final XMLOutputter outputter = new XMLOutputter();

    try {//from w  w w . j a  v  a  2  s  .c  om
        outputter.output(xmlRootNode, sw);
        return sw.getBuffer().toString();
    } catch (final IOException e) {
        throw new RuntimeException("Failed to parse element", e);
    }
}

From source file:org.apache.kylin.rest.security.PasswordPlaceholderConfigurer.java

/**
 * The PasswordPlaceholderConfigurer will read Kylin properties as the Spring resource
 *///from  ww  w  .  jav a 2 s .co m
public PasswordPlaceholderConfigurer() throws IOException {
    Resource[] resources = new Resource[1];
    //Properties prop = KylinConfig.getKylinProperties();
    Properties prop = getAllKylinProperties();
    StringWriter writer = new StringWriter();
    prop.store(new PrintWriter(writer), "kylin properties");
    String propString = writer.getBuffer().toString();
    IOUtils.closeQuietly(writer);
    InputStream is = IOUtils.toInputStream(propString, Charset.defaultCharset());
    resources[0] = new InputStreamResource(is);
    this.setLocations(resources);
}

From source file:jp.mathes.databaseWiki.wiki.SQLButtonPlugin.java

@SuppressWarnings("unchecked")
@Override/*from   www. j  av  a  2 s.  c o  m*/
public void process(final Document doc, final String fieldname, final String user, final String password,
        final Backend backend) throws PluginException {
    Field<String> field = doc.getAllFields().get(fieldname);
    String renderedText = field.getValue();
    if (renderedText == null) {
        return;
    }
    Configuration conf = new Configuration();
    conf.setTagSyntax(Configuration.SQUARE_BRACKET_TAG_SYNTAX);
    Matcher buttonMatcher = SQLButtonPlugin.REGEX.matcher(renderedText);
    while (buttonMatcher.find()) {
        String statement = buttonMatcher.group(1);
        statement = statement.replace("&quot;", "\"").replace("&#39;", "'");
        Template template;
        try {
            template = new Template("name", new StringReader(statement), conf);
            HashMap<String, Object> data = new HashMap<String, Object>();
            data.put("doc", doc);
            data.put("fields", doc.getAllFields());
            StringWriter sw = new StringWriter();
            template.process(data, sw);
            statement = sw.getBuffer().toString();
            StringBuilder sb = new StringBuilder(
                    "<form class=\"execute\" method=\"post\" action=\"../../../sql\">");
            sb.append("<input type=\"hidden\" name=\"statement\" value=\"")
                    .append(StringEscapeUtils.escapeXml(statement)).append("\" />")
                    .append("<input type=\"hidden\" name=\"_db\" value=\"").append(doc.getDatabase())
                    .append("\" />").append("<input type=\"hidden\" name=\"_table\" value=\"")
                    .append(doc.getTable()).append("\" />")
                    .append("<input type=\"hidden\" name=\"name\" value=\"").append(doc.getName())
                    .append("\" />").append("<input type=\"submit\" name=\"execute\" value=\"execute\" />")
                    .append("</form>");
            renderedText = renderedText.replace(buttonMatcher.group(0), sb.toString());
            field.setValue(renderedText);
        } catch (TemplateException e) {
            throw new PluginException(e);
        } catch (IOException e) {
            throw new PluginException(e);
        }
    }
}

From source file:com.github.ipaas.ifw.front.directive.HtmlDirective.java

public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
        throws TemplateException, IOException {
    String framework = "";
    TemplateModel paramValue = (TemplateModel) params.get(FRAMEWORK_NAME);
    if (paramValue != null) {
        framework = ((TemplateScalarModel) paramValue).getAsString();
    }// ww  w  .  j av a 2  s .com

    String tagBeginHtml = tagBegin(params);

    Writer out = env.getOut();
    if (body != null) {
        try {
            if (StringUtils.isNotBlank(framework)) {
                this.fisRes.setFramework(this.fisRes.getResourceUri(framework));
            }
            out.write(tagBeginHtml);

            StringWriter sOut = new StringWriter();
            body.render(sOut);

            out.write(this.fisRes.renderResponse(sOut.getBuffer().toString()));
        } catch (FisException e) {
            throw new TemplateException(e.getMessage(), e, env);
        }
        out.write("\n</html>");
    }

}

From source file:com.kactech.otj.Utils.java

public static String toRawPublicInfo(PublicKey publicKey, boolean escaped) {
    StringWriter sw = new StringWriter();
    PEMWriter pemw = new PEMWriter(sw);
    try {/*from w  ww  .j a  v  a  2s . c om*/
        pemw.writeObject(publicKey);
        pemw.flush();
        pemw.close();
    } catch (IOException e) {
        // with StringBuffer? I don't think so, but throw that
        throw new RuntimeException(e);
    }
    String str = sw.getBuffer().toString();
    byte[] out = pack(ByteBuffer.wrap(bytes(str, US_ASCII)));
    str = base64EncodeString(out, true);
    return (escaped ? "- " : "") + "-----BEGIN PUBLIC KEY-----\n" + str + (escaped ? "- " : "")
            + "-----END PUBLIC KEY-----\n";
}