Search in sources :

Example 6 with StringWriter

use of java.io.StringWriter in project camel by apache.

the class ExpressionBuilder method exchangeExceptionStackTraceExpression.

/**
     * Returns an expression for an exception stacktrace set on the exchange
     *
     * @return an expression object which will return the exception stacktrace set on the exchange
     */
public static Expression exchangeExceptionStackTraceExpression() {
    return new ExpressionAdapter() {

        public Object evaluate(Exchange exchange) {
            Exception exception = exchange.getException();
            if (exception == null) {
                exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
            }
            if (exception != null) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                exception.printStackTrace(pw);
                IOHelper.close(pw, sw);
                return sw.toString();
            } else {
                return null;
            }
        }

        @Override
        public String toString() {
            return "exchangeExceptionStackTrace";
        }
    };
}
Also used : Exchange(org.apache.camel.Exchange) StringWriter(java.io.StringWriter) NoTypeConversionAvailableException(org.apache.camel.NoTypeConversionAvailableException) NoSuchLanguageException(org.apache.camel.NoSuchLanguageException) InvalidPayloadException(org.apache.camel.InvalidPayloadException) NoSuchEndpointException(org.apache.camel.NoSuchEndpointException) ExpressionAdapter(org.apache.camel.support.ExpressionAdapter) PrintWriter(java.io.PrintWriter)

Example 7 with StringWriter

use of java.io.StringWriter in project camel by apache.

the class DefaultExchangeFormatter method format.

public String format(Exchange exchange) {
    Message in = exchange.getIn();
    StringBuilder sb = new StringBuilder();
    if (showAll || showExchangeId) {
        if (multiline) {
            sb.append(SEPARATOR);
        }
        sb.append(style("Id")).append(exchange.getExchangeId());
    }
    if (showAll || showExchangePattern) {
        if (multiline) {
            sb.append(SEPARATOR);
        }
        sb.append(style("ExchangePattern")).append(exchange.getPattern());
    }
    if (showAll || showProperties) {
        if (multiline) {
            sb.append(SEPARATOR);
        }
        sb.append(style("Properties")).append(sortMap(exchange.getProperties()));
    }
    if (showAll || showHeaders) {
        if (multiline) {
            sb.append(SEPARATOR);
        }
        sb.append(style("Headers")).append(sortMap(in.getHeaders()));
    }
    if (showAll || showBodyType) {
        if (multiline) {
            sb.append(SEPARATOR);
        }
        sb.append(style("BodyType")).append(getBodyTypeAsString(in));
    }
    if (showAll || showBody) {
        if (multiline) {
            sb.append(SEPARATOR);
        }
        String body = getBodyAsString(in);
        if (skipBodyLineSeparator) {
            body = StringHelper.replaceAll(body, LS, "");
        }
        sb.append(style("Body")).append(body);
    }
    if (showAll || showException || showCaughtException) {
        // try exception on exchange first
        Exception exception = exchange.getException();
        boolean caught = false;
        if ((showAll || showCaughtException) && exception == null) {
            // fallback to caught exception
            exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
            caught = true;
        }
        if (exception != null) {
            if (multiline) {
                sb.append(SEPARATOR);
            }
            if (caught) {
                sb.append(style("CaughtExceptionType")).append(exception.getClass().getCanonicalName());
                sb.append(style("CaughtExceptionMessage")).append(exception.getMessage());
            } else {
                sb.append(style("ExceptionType")).append(exception.getClass().getCanonicalName());
                sb.append(style("ExceptionMessage")).append(exception.getMessage());
            }
            if (showAll || showStackTrace) {
                StringWriter sw = new StringWriter();
                exception.printStackTrace(new PrintWriter(sw));
                sb.append(style("StackTrace")).append(sw.toString());
            }
        }
    }
    if (showAll || showOut) {
        if (exchange.hasOut()) {
            Message out = exchange.getOut();
            if (showAll || showHeaders) {
                if (multiline) {
                    sb.append(SEPARATOR);
                }
                sb.append(style("OutHeaders")).append(sortMap(out.getHeaders()));
            }
            if (showAll || showBodyType) {
                if (multiline) {
                    sb.append(SEPARATOR);
                }
                sb.append(style("OutBodyType")).append(getBodyTypeAsString(out));
            }
            if (showAll || showBody) {
                if (multiline) {
                    sb.append(SEPARATOR);
                }
                String body = getBodyAsString(out);
                if (skipBodyLineSeparator) {
                    body = StringHelper.replaceAll(body, LS, "");
                }
                sb.append(style("OutBody")).append(body);
            }
        } else {
            if (multiline) {
                sb.append(SEPARATOR);
            }
            sb.append(style("Out: null"));
        }
    }
    if (maxChars > 0) {
        StringBuilder answer = new StringBuilder();
        for (String s : sb.toString().split(SEPARATOR)) {
            if (s != null) {
                if (s.length() > maxChars) {
                    s = s.substring(0, maxChars);
                    answer.append(s).append("...");
                } else {
                    answer.append(s);
                }
                if (multiline) {
                    answer.append(LS);
                }
            }
        }
        // switch string buffer
        sb = answer;
    }
    if (multiline) {
        sb.insert(0, "Exchange[");
        sb.append("]");
        return sb.toString();
    } else {
        // get rid of the leading space comma if needed
        if (sb.length() > 0 && sb.charAt(0) == ',' && sb.charAt(1) == ' ') {
            sb.replace(0, 2, "");
        }
        sb.insert(0, "Exchange[");
        sb.append("]");
        return sb.toString();
    }
}
Also used : Message(org.apache.camel.Message) StringWriter(java.io.StringWriter) PrintWriter(java.io.PrintWriter)

Example 8 with StringWriter

use of java.io.StringWriter in project camel by apache.

the class ModelHelper method dumpModelAsXml.

/**
     * Dumps the definition as XML
     *
     * @param context    the CamelContext, if <tt>null</tt> then {@link org.apache.camel.spi.ModelJAXBContextFactory} is not in use
     * @param definition the definition, such as a {@link org.apache.camel.NamedNode}
     * @return the output in XML (is formatted)
     * @throws JAXBException is throw if error marshalling to XML
     */
public static String dumpModelAsXml(CamelContext context, NamedNode definition) throws JAXBException {
    JAXBContext jaxbContext = getJAXBContext(context);
    final Map<String, String> namespaces = new LinkedHashMap<>();
    // gather all namespaces from the routes or route which is stored on the expression nodes
    if (definition instanceof RoutesDefinition) {
        List<RouteDefinition> routes = ((RoutesDefinition) definition).getRoutes();
        for (RouteDefinition route : routes) {
            extractNamespaces(route, namespaces);
        }
    } else if (definition instanceof RouteDefinition) {
        RouteDefinition route = (RouteDefinition) definition;
        extractNamespaces(route, namespaces);
    }
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    StringWriter buffer = new StringWriter();
    marshaller.marshal(definition, buffer);
    XmlConverter xmlConverter = newXmlConverter(context);
    String xml = buffer.toString();
    Document dom;
    try {
        dom = xmlConverter.toDOMDocument(xml, null);
    } catch (Exception e) {
        throw new TypeConversionException(xml, Document.class, e);
    }
    // Add additional namespaces to the document root element
    Element documentElement = dom.getDocumentElement();
    for (String nsPrefix : namespaces.keySet()) {
        String prefix = nsPrefix.equals("xmlns") ? nsPrefix : "xmlns:" + nsPrefix;
        documentElement.setAttribute(prefix, namespaces.get(nsPrefix));
    }
    // We invoke the type converter directly because we need to pass some custom XML output options
    Properties outputProperties = new Properties();
    outputProperties.put(OutputKeys.INDENT, "yes");
    outputProperties.put(OutputKeys.STANDALONE, "yes");
    try {
        return xmlConverter.toStringFromDocument(dom, outputProperties);
    } catch (TransformerException e) {
        throw new IllegalStateException("Failed converting document object to string", e);
    }
}
Also used : Marshaller(javax.xml.bind.Marshaller) TypeConversionException(org.apache.camel.TypeConversionException) Element(org.w3c.dom.Element) JAXBContext(javax.xml.bind.JAXBContext) Document(org.w3c.dom.Document) Properties(java.util.Properties) TransformerException(javax.xml.transform.TransformerException) JAXBException(javax.xml.bind.JAXBException) TypeConversionException(org.apache.camel.TypeConversionException) LinkedHashMap(java.util.LinkedHashMap) XmlConverter(org.apache.camel.converter.jaxp.XmlConverter) StringWriter(java.io.StringWriter) TransformerException(javax.xml.transform.TransformerException)

Example 9 with StringWriter

use of java.io.StringWriter in project camel by apache.

the class LogBodyWithNewLineTest method setUp.

public void setUp() throws Exception {
    super.setUp();
    writer = new StringWriter();
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    Appender appender = WriterAppender.newBuilder().setLayout(PatternLayout.newBuilder().withPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN).build()).setTarget(writer).setName("Writer").build();
    appender.start();
    config.addAppender(appender);
    config.getRootLogger().removeAppender("Writer");
    config.getRootLogger().addAppender(appender, Level.INFO, null);
    ctx.updateLoggers();
}
Also used : WriterAppender(org.apache.logging.log4j.core.appender.WriterAppender) Appender(org.apache.logging.log4j.core.Appender) StringWriter(java.io.StringWriter) Configuration(org.apache.logging.log4j.core.config.Configuration) LoggerContext(org.apache.logging.log4j.core.LoggerContext)

Example 10 with StringWriter

use of java.io.StringWriter in project camel by apache.

the class GenerateXmlTest method dump.

protected void dump(RouteContainer context) throws Exception {
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    StringWriter buffer = new StringWriter();
    marshaller.marshal(context, buffer);
    log.info("Created: " + buffer);
    assertNotNull(buffer);
    String out = buffer.toString();
    assertTrue("Should contain the description", out.indexOf("This is a description of the route") > 0);
}
Also used : Marshaller(javax.xml.bind.Marshaller) StringWriter(java.io.StringWriter)

Aggregations

StringWriter (java.io.StringWriter)3175 PrintWriter (java.io.PrintWriter)1057 Test (org.junit.Test)612 IOException (java.io.IOException)516 StringReader (java.io.StringReader)232 Writer (java.io.Writer)211 StreamResult (javax.xml.transform.stream.StreamResult)207 File (java.io.File)194 InputStreamReader (java.io.InputStreamReader)140 HashMap (java.util.HashMap)136 Transformer (javax.xml.transform.Transformer)125 InputStream (java.io.InputStream)119 Map (java.util.Map)116 ArrayList (java.util.ArrayList)106 DOMSource (javax.xml.transform.dom.DOMSource)99 BufferedReader (java.io.BufferedReader)96 ByteArrayInputStream (java.io.ByteArrayInputStream)84 Reader (java.io.Reader)77 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)75 HttpServletResponse (javax.servlet.http.HttpServletResponse)73