Example usage for java.io Writer toString

List of usage examples for java.io Writer toString

Introduction

In this page you can find the example usage for java.io Writer toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.broadleafcommerce.core.web.processor.ProductOptionsProcessor.java

private void writeJSONToModel(Arguments arguments, String modelKey, Object o) {
    try {/*from w w w.ja v a2s .c  o m*/
        String jsonValue = JSON_CACHE.get(o);
        if (jsonValue == null) {
            ObjectMapper mapper = new ObjectMapper();
            Writer strWriter = new StringWriter();
            mapper.writeValue(strWriter, o);
            jsonValue = strWriter.toString();
            JSON_CACHE.put(o, jsonValue);
        }
        addToModel(arguments, modelKey, jsonValue);
    } catch (Exception ex) {
        LOG.error("There was a problem writing the product option map to JSON", ex);
    }
}

From source file:com.sap.prd.mobile.ios.mios.xcodeprojreader.jaxb.JAXBPlistParserTest.java

@Test
public void saveToWriter() throws Exception {
    JAXBPlistParser parser = new JAXBPlistParser();
    Plist plist = parser.load(fileName);

    Writer output = new StringWriter();
    parser.save(plist, output);//from  w  w w .ja  v  a  2  s  .co  m

    DocumentBuilder db = initDocumentBuilder();
    Document expected = db.parse(new File(fileName));
    Document actual = db.parse(new ByteArrayInputStream(output.toString().getBytes()));
    assertXMLEqual(expected, actual);
}

From source file:jodtemplate.pptx.PPTXDocumentProcessor.java

@Override
public void process(final Map<String, Object> context, final Resources resources) throws JODTemplateException {
    final ExpressionHandler expressionHandler = configuration.getExpressionHandler();
    try {//from  w  w w  .  ja  v a 2s  .com
        final Presentation presentation = pptxReader.read(resources);
        for (final Slide slide : presentation.getSlides()) {
            final String slideXmlPath = FilenameUtils
                    .normalize(presentation.getFullPath() + slide.getRelationship().getTarget(), true);
            final Resource slideRes = resources.getResource(Utils.removePrefixSeparator(slideXmlPath));
            Document dom;
            try (final InputStream is = slideRes.getInputStream()) {
                dom = jdomHelper.createJDOMDocument(is);
            }

            for (final DomProcessor preprocessor : configuration.getPreprocessors()) {
                dom = preprocessor.process(context, dom, slide, resources, configuration);
            }

            final String rawContents = jdomHelper.getRawContents(dom);
            final Parser parser = configuration.getParserFactory().createParser();
            final List<String> parsedParts = parser.parse(rawContents);
            final StringBuilder translatedContents = new StringBuilder();
            for (final String parsedPart : parsedParts) {
                if (expressionHandler.isExpression(parsedPart)) {
                    translatedContents.append(expressionHandler.translateExpression(parsedPart));
                } else {
                    translatedContents.append(parsedPart);
                }
            }
            final Writer writer = new StringWriter();
            expressionHandler.getEngine().process(slide.getRelationship().getId(),
                    translatedContents.toString(), context, writer);
            final String filledContents = writer.toString();
            dom = jdomHelper.createJDOMDocument(filledContents);

            for (final DomProcessor postprocessor : configuration.getPostprocessors()) {
                dom = postprocessor.process(context, dom, slide, resources, configuration);
            }

            try (final OutputStream os = slideRes.getOutputStream()) {
                jdomHelper.write(dom, os);
            }

        }
        pptxWriter.write(resources, presentation);

    } catch (IOException | XMLStreamException | JDOMException e) {
        throw new JODTemplateException("Template processing error", e);
    }
}

From source file:nl.cyso.vsphere.client.docs.Readme.java

private String getSynopsisSection() {
    StringBuilder section = new StringBuilder();
    section.append("SYNOPSIS\n");
    section.append("--------\n");

    HelpFormatter help = new HelpFormatter();
    help.setSyntaxPrefix("");

    Writer str = new StringWriter();
    PrintWriter pw = new PrintWriter(str);

    help.printUsage(pw, 1000, Version.getVersion().getProjectName(), ConfigModes.getMode("ROOT"));
    section.append("\t\n\t" + str.toString() + "\n");

    for (String m : ConfigModes.getModes().keySet()) {
        if (m == "ROOT") {
            continue;
        }//from w w  w  .j  a v  a  2  s.c o m
        str = new StringWriter();
        pw = new PrintWriter(str);
        help.printUsage(pw, 1000, Version.getVersion().getProjectName(), ConfigModes.getMode(m));
        section.append(String.format("**%s**\n\n", m.toString()));
        section.append("\t" + str.toString() + "\n");
    }
    return section.toString();
}

From source file:be.fedict.eid.pkira.blm.model.mail.MailTemplateBean.java

/**
 * {@inheritDoc}/*from   w  w  w .  j  a v  a2  s .c  o  m*/
 */
@Override
public String createMailMessage(String templateName, Map<String, Object> parameters, String localeStr) {
    parameters.put("configuration", configurationEntryQuery.getAsMap());

    Locale locale = Locale.ENGLISH;
    try {
        locale = LocaleUtils.toLocale(localeStr);
    } catch (Exception e) {
        log.error("Invalid locale string: " + localeStr, e);
    }

    try {
        Writer out = new StringWriter();
        Template temp = configuration.getTemplate(templateName, locale);
        temp.process(parameters, out);
        out.flush();

        return out.toString();
    } catch (IOException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Error creating mail message", e);
        return null;
    } catch (TemplateException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Error creating mail message", e);
        return null;
    }
}

From source file:it.unibs.sandroide.lib.BLEContext.java

public static JSONObject findRestApi(String apiName) {
    JSONObject ret = null;/* ww  w  . ja  v a  2s  .  co m*/
    if (allRestApis == null || !allRestApis.has(apiName)) {
        // Load Rest APIs from JSON/XML files
        int resid = context.getResources().getIdentifier(apiName, "raw", context.getPackageName());
        //InputStream is = context.getResources().openRawResource(R.raw.rest_apis);
        InputStream is = context.getResources().openRawResource(resid);

        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            try {
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            allRestApis.put(apiName, new JSONObject(writer.toString()));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    try {
        ret = allRestApis.getJSONObject(apiName);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return ret;
}

From source file:ai.grakn.engine.controller.SystemController.java

@GET
@Path("/metrics")
@ApiOperation(value = "Exposes internal metrics")
@ApiImplicitParams({/*from   www. ja  va2 s  . c o  m*/
        @ApiImplicitParam(name = FORMAT, value = "prometheus", dataType = "string", paramType = "path") })
private String getMetrics(Request request, Response response) throws IOException {
    response.header(CACHE_CONTROL, "must-revalidate,no-cache,no-store");
    response.status(HttpServletResponse.SC_OK);
    Optional<String> format = Optional.ofNullable(request.queryParams(FORMAT));
    String dFormat = format.orElse(JSON);
    if (dFormat.equals(PROMETHEUS)) {
        // Prometheus format for the metrics
        response.type(PROMETHEUS_CONTENT_TYPE);
        final Writer writer1 = new StringWriter();
        TextFormat.write004(writer1, this.prometheusRegistry.metricFamilySamples());
        return writer1.toString();
    } else if (dFormat.equals(JSON)) {
        // Json/Dropwizard format
        response.type(APPLICATION_JSON);
        final ObjectWriter writer = mapper.writer();
        try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
            writer.writeValue(output, this.metricRegistry);
            return new String(output.toByteArray(), "UTF-8");
        }
    } else {
        throw new IllegalArgumentException("Unexpected format " + dFormat);
    }
}

From source file:beans.LogSmtp.java

@Override
protected void append(ILoggingEvent eventObject) {
    try {//from   w w  w  .jav  a 2  s. co m
        if (ApplicationContext.get().conf().sendErrorEmails) {
            GsMailer.GsMailConfiguration mail = new GsMailer.GsMailConfiguration();
            // TODO : move configuration to configuration files.
            // TODO : add dev mode support
            mail.setSubject("Error occured");
            mail.addRecipient(GsMailer.RecipientType.TO, "guym@gigaspaces.com", "Guy Mograbi");
            mail.setBodyText(eventObject.getFormattedMessage());
            mail.setFrom("it@gigaspaces.com", "gigaspaces");
            ApplicationContext.get().getMailer().send(mail);
        }
    } catch (Exception e) {
        Writer writer = new StringWriter();
        e.printStackTrace(new PrintWriter(writer));
        // if we write errors to log here, we will end up here again.. infinite loop.. :(
        File file = new File("appender_problems_" + System.currentTimeMillis() + ".error");
        try {
            FileUtils.writeStringToFile(file, writer.toString());
        } catch (IOException e1) {
            System.out.println("unable to print appender errors.");
        }

    }

}

From source file:org.nuxeo.ecm.platform.ec.notification.email.EmailHelper.java

protected void sendmail0(Map<String, Object> mail)
        throws MessagingException, IOException, TemplateException, LoginException, RenderingException {

    Session session = getSession();/*w  w w. java 2  s  .  c  o  m*/
    if (javaMailNotAvailable || session == null) {
        log.warn("Not sending email since JavaMail is not configured");
        return;
    }

    // Construct a MimeMessage
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(session.getProperty("mail.from")));
    Object to = mail.get("mail.to");
    if (!(to instanceof String)) {
        log.error("Invalid email recipient: " + to);
        return;
    }
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String) to, false));

    RenderingService rs = Framework.getService(RenderingService.class);

    DocumentRenderingContext context = new DocumentRenderingContext();
    context.remove("doc");
    context.putAll(mail);
    context.setDocument((DocumentModel) mail.get("document"));
    context.put("Runtime", Framework.getRuntime());

    String customSubjectTemplate = (String) mail.get(NotificationConstants.SUBJECT_TEMPLATE_KEY);
    if (customSubjectTemplate == null) {
        String subjTemplate = (String) mail.get(NotificationConstants.SUBJECT_KEY);
        Template templ = new Template("name", new StringReader(subjTemplate), stringCfg);

        Writer out = new StringWriter();
        templ.process(mail, out);
        out.flush();

        msg.setSubject(out.toString(), "UTF-8");
    } else {
        rs.registerEngine(new NotificationsRenderingEngine(customSubjectTemplate));

        LoginContext lc = Framework.login();

        Collection<RenderingResult> results = rs.process(context);
        String subjectMail = "<HTML><P>No parsing Succeded !!!</P></HTML>";

        for (RenderingResult result : results) {
            subjectMail = (String) result.getOutcome();
        }
        subjectMail = NotificationServiceHelper.getNotificationService().getEMailSubjectPrefix() + subjectMail;
        msg.setSubject(subjectMail, "UTF-8");

        lc.logout();
    }

    msg.setSentDate(new Date());

    rs.registerEngine(new NotificationsRenderingEngine((String) mail.get(NotificationConstants.TEMPLATE_KEY)));

    LoginContext lc = Framework.login();

    Collection<RenderingResult> results = rs.process(context);
    String bodyMail = "<HTML><P>No parsing Succedeed !!!</P></HTML>";

    for (RenderingResult result : results) {
        bodyMail = (String) result.getOutcome();
    }

    lc.logout();

    rs.unregisterEngine("ftl");

    msg.setContent(bodyMail, "text/html; charset=utf-8");

    // Send the message.
    Transport.send(msg);
}