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.eclipse.hudson.plugins.PluginInstallationJob.java

public static String getStackTrace(Throwable throwable) {
    Writer result = new StringWriter();
    PrintWriter printWriter = new PrintWriter(result);
    throwable.printStackTrace(printWriter);
    return result.toString();
}

From source file:helper.SerializationHelper.java

public static String serializeObject(Object object) {
    ObjectMapper mapper = new ObjectMapper();
    Writer strWriter = new StringWriter();
    try {/*w  w w. ja va2  s. co m*/
        mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        mapper.writeValue(strWriter, object);
    } catch (Exception e) {
        System.out.println(e);
    }
    return strWriter.toString();
}

From source file:no.acando.xmltordf.doclet.JsonJavadocExampleRunner.java

public static String formatXml(String unformattedXml) {
    try {/*from ww  w  .  java  2  s. co  m*/
        final Document document = parseXmlFile(unformattedXml);

        OutputFormat format = new OutputFormat(document);
        format.setLineWidth(65);
        format.setIndenting(true);
        format.setIndent(2);
        Writer out = new StringWriter();
        XMLSerializer serializer = new XMLSerializer(out, format);
        serializer.serialize(document);

        return out.toString().replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "").trim();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:ch.entwine.weblounge.common.impl.util.doc.EndpointDocumentationGenerator.java

/**
 * Handles the replacement of the variable strings within textual templates
 * and also allows the setting of variables for the control of logical
 * branching within the text template as well<br/>
 * Uses and expects freemarker (http://freemarker.org/) style templates (that
 * is using ${name} as the marker for a replacement)<br/>
 * NOTE: These should be compatible with Velocity
 * (http://velocity.apache.org/) templates if you use the formal notation
 * (formal: ${variable}, shorthand: $variable)
 * /*  ww w.j  a  v a  2  s  .c o m*/
 * @param templateName
 *          this is the key to cache the template under
 * @param textTemplate
 *          a freemarker/velocity style text template, cannot be null or empty
 *          string
 * @param data
 *          a set of replacement values which are in the map like so:<br/>
 *          key => value (String => Object)<br/>
 *          "username" => "aaronz"<br/>
 * @return the processed template
 */
private static String processTextTemplate(String templateName, String textTemplate, Map<String, Object> data) {

    if (freemarkerConfig == null)
        throw new IllegalStateException("FreemarkerConfig is not initialized");
    if (StringUtils.trimToNull(templateName) == null)
        throw new IllegalArgumentException("The templateName cannot be null or empty string, "
                + "please specify a key name to use when processing this template (can be anything moderately unique)");
    if (data == null || data.size() == 0)
        return textTemplate;
    if (StringUtils.trimToNull(textTemplate) == null)
        throw new IllegalArgumentException("The textTemplate cannot be null or empty string, "
                + "please pass in at least something in the template or do not call this method");

    // get the template
    Template template = null;
    try {
        template = new Template(templateName, new StringReader(textTemplate), freemarkerConfig);
    } catch (ParseException e) {
        String msg = "Failure while parsing the Doc template (" + templateName + "), template is invalid: " + e
                + " :: template=" + textTemplate;
        logger.error(msg);
        throw new RuntimeException(msg, e);
    } catch (IOException e) {
        throw new RuntimeException("Failure while creating freemarker template", e);
    }

    // process the template
    String result = null;
    try {
        Writer output = new StringWriter();
        template.process(data, output);
        result = output.toString();
        logger.debug("Generated complete document ({} chars) from template ({})", result.length(),
                templateName);
    } catch (TemplateException e) {
        result = "Failed while processing the template (" + templateName + "): " + e.getMessage() + "\n";
        result += "Template: " + textTemplate + "\n";
        result += "Data: " + data;
        logger.error("Failed while processing the Doc template ({}): {}", templateName, e);
    } catch (IOException e) {
        throw new RuntimeException("Failure while sending freemarker output to stream", e);
    }

    return result;
}

From source file:org.apache.hadoop.mapred.GenThread.java

public static String getErrorMessage(Exception ex) {
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    ex.printStackTrace(printWriter);/*from ww w .  ja  v  a2 s  .  co  m*/
    return ex.getMessage() + "\n" + result.toString() + "\n";
}

From source file:org.clickframes.VelocityHelper.java

public static String runMacro(Map<String, Object> params, String macro) {
    try {/*  w w  w.  jav a2 s. com*/
        initVelocity(null);
    } catch (Exception e1) {
        throw new RuntimeException("Could not initialize velocity", e1);
    }

    Template t;
    try {
        boolean allowOverrides = false;
        if (allowOverrides && Velocity.resourceExists(macro + OVERRIDE_SUFFIX)) {
            t = Velocity.getTemplate(macro + OVERRIDE_SUFFIX);
        } else {
            t = Velocity.getTemplate(macro);
        }

        VelocityContext ctx = new VelocityContext();
        if (params != null) {
            for (String key : params.keySet()) {
                ctx.put(key, params.get(key));
            }
        }

        Writer writer = new StringWriter();

        t.merge(ctx, writer);
        writer.close();

        return writer.toString();
    } catch (Exception e) {
        throw new RuntimeException("Error occurred while writing the page", e);
    }
}

From source file:com.sonar.maven.it.ItUtils.java

/**
 * Creates a settings xml with a sonar profile, containing all the given properties
 * Also adds repox to continue to use QAed artifacts 
 *//*from  w w  w  .  ja v a 2s.c o  m*/
public static String createSettingsXml(Map<String, String> props) throws Exception {
    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = docBuilder.newDocument();

    Element settings = doc.createElement("settings");
    Element profiles = doc.createElement("profiles");
    Element profile = doc.createElement("profile");

    Element id = doc.createElement("id");
    id.setTextContent("sonar");

    Element properties = doc.createElement("properties");

    for (Map.Entry<String, String> e : props.entrySet()) {
        Element el = doc.createElement(e.getKey());
        el.setTextContent(e.getValue());
        properties.appendChild(el);
    }

    profile.appendChild(id);
    profile.appendChild(properties);
    profile.appendChild(createRepositories(doc));
    profile.appendChild(createPluginRepositories(doc));

    profiles.appendChild(profile);
    settings.appendChild(profiles);
    doc.appendChild(settings);

    Writer writer = new StringWriter();
    Transformer tf = TransformerFactory.newInstance().newTransformer();
    tf.transform(new DOMSource(doc), new StreamResult(writer));
    return writer.toString();
}

From source file:com.evolveum.midpoint.web.component.message.OpResult.java

public static OpResult getOpResult(PageBase page, OperationResult result)
        throws SchemaException, RuntimeException {
    OpResult opResult = new OpResult();
    Validate.notNull(result, "Operation result must not be null.");
    Validate.notNull(result.getStatus(), "Operation result status must not be null.");

    opResult.message = result.getMessage();
    opResult.operation = result.getOperation();
    opResult.status = result.getStatus();
    opResult.count = result.getCount();//from   ww w . j av a2s .c o  m

    if (result.getCause() != null) {
        Throwable cause = result.getCause();
        opResult.exceptionMessage = cause.getMessage();

        Writer writer = new StringWriter();
        cause.printStackTrace(new PrintWriter(writer));
        opResult.exceptionsStackTrace = writer.toString();
    }

    if (result.getParams() != null) {
        for (Map.Entry<String, Serializable> entry : result.getParams().entrySet()) {
            String paramValue = null;
            Object value = entry.getValue();
            if (value != null) {
                paramValue = value.toString();
            }

            opResult.getParams().add(new Param(entry.getKey(), paramValue));
        }
    }

    if (result.getContext() != null) {
        for (Map.Entry<String, Serializable> entry : result.getContext().entrySet()) {
            String contextValue = null;
            Object value = entry.getValue();
            if (value != null) {
                contextValue = value.toString();
            }

            opResult.getContexts().add(new Context(entry.getKey(), contextValue));
        }
    }

    if (result.getSubresults() != null) {
        for (OperationResult subresult : result.getSubresults()) {
            opResult.getSubresults().add(OpResult.getOpResult(page, subresult));
        }
    }

    try {
        OperationResultType resultType = result.createOperationResultType();
        ObjectFactory of = new ObjectFactory();
        opResult.xml = page.getPrismContext().serializeAtomicValue(of.createOperationResult(resultType),
                PrismContext.LANG_XML);
    } catch (SchemaException | RuntimeException ex) {
        String m = "Can't create xml: " + ex;
        //         error(m);
        opResult.xml = "<?xml version='1.0'?><message>" + StringEscapeUtils.escapeXml(m) + "</message>";
        throw ex;
    }
    return opResult;
}

From source file:de.extra.client.plugins.responseprocessplugin.filesystem.ExtraMessageReturnDataExtractor.java

/**
 * Die eXTra-Nachricht wird im Log ausgegeben, wenn der messageLogger auf
 * Debug gesetzt ist.//from   w w  w  . ja  v a  2s  . c o  m
 * 
 * @param marshaller
 * @param extraResponse
 */
static void printResult(IExtraMarschaller marshaller, final ResponseTransport extraResponse) {
    operation_logger.info("Nachricht vom eXTra-Server erhalten");
    message_response_logger.info("Nachricht vom eXTra-Server erhalten:");
    Logger messageLogger = ExtraMessageReturnDataExtractor.message_response_logger;
    if (messageLogger.isDebugEnabled()) {
        try {
            final Writer writer = new StringWriter();
            final StreamResult streamResult = new StreamResult(writer);

            marshaller.marshal(extraResponse, streamResult);
            messageLogger.debug(writer.toString());
        } catch (final XmlMappingException xmlException) {
            messageLogger.error("XmlMappingException beim Lesen des Results ", xmlException);
        } catch (final IOException ioException) {
            messageLogger.debug("IOException beim Lesen des Results ", ioException);
        }
    }
}

From source file:Main.java

public static String xml(TransformerFactory transformerFactory, Node node) {
    Writer writer = new StringWriter();
    DOMSource source = new DOMSource(node);
    StreamResult result = new StreamResult(writer);
    try {/*  ww w .  j  a v  a2 s .  c  o m*/
        transformerFactory.newTransformer().transform(source, result);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
    return writer.toString().replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
}