Java 类org.apache.camel.TypeConversionException 实例源码

项目:flowable-engine    文件:ExchangeUtils.java   
/**
 * Gets the value of the Camel header that contains the userId to be set as the process initiator. Returns null if no header name was specified on the Camel route.
 *
 * @param exchange The Camel Exchange object
 * @param endpoint The endPoint implementation
 * @return The userId of the user to be set as the process initiator
 */
public static String prepareInitiator(Exchange exchange, FlowableEndpoint endpoint) {

    String initiator = null;
    if (endpoint.isSetProcessInitiator()) {
        try {
            initiator = exchange.getIn().getHeader(endpoint.getProcessInitiatorHeaderName(), String.class);
        } catch (TypeConversionException e) {
            throw new FlowableException("Initiator header '" +
                    endpoint.getProcessInitiatorHeaderName() + "': Value must be of type String.", e);
        }

        if (StringUtils.isEmpty(initiator)) {
            throw new FlowableException("Initiator header '" +
                    endpoint.getProcessInitiatorHeaderName() + "': Value must be provided");
        }
    }
    return initiator;
}
项目:Camel    文件:SimpleBuilderTest.java   
public void testResultType() throws Exception {
    exchange.getIn().setBody("foo");
    exchange.getIn().setHeader("cool", true);

    assertEquals("foo", SimpleBuilder.simple("${body}", String.class).evaluate(exchange, Object.class));
    try {
        // error during conversion
        SimpleBuilder.simple("${body}", int.class).evaluate(exchange, Object.class);
        fail("Should have thrown exception");
    } catch (TypeConversionException e) {
        assertIsInstanceOf(NumberFormatException.class, e.getCause().getCause());
    }

    assertEquals(true, SimpleBuilder.simple("${header.cool}", boolean.class).evaluate(exchange, Object.class));
    assertEquals("true", SimpleBuilder.simple("${header.cool}", String.class).evaluate(exchange, Object.class));
    // not possible
    assertEquals(null, SimpleBuilder.simple("${header.cool}", int.class).evaluate(exchange, Object.class));

    assertEquals(true, SimpleBuilder.simple("${header.cool}").resultType(Boolean.class).evaluate(exchange, Object.class));
    assertEquals("true", SimpleBuilder.simple("${header.cool}").resultType(String.class).evaluate(exchange, Object.class));
    // not possible
    assertEquals(null, SimpleBuilder.simple("${header.cool}").resultType(int.class).evaluate(exchange, Object.class));

    // should be convertable to integers
    assertEquals(11, SimpleBuilder.simple("11", int.class).evaluate(exchange, Object.class));
}
项目:Camel    文件:JmsMessageTypeTest.java   
@Override
@SuppressWarnings("unchecked")
public <T> T convertTo(Class<T> type, Exchange exchange, Object value) throws TypeConversionException {
    if (type.isAssignableFrom(String.class)) {
        return (T) ("Hello " + ((MyFooBean)value).getName());
    }
    if (type.isAssignableFrom(byte[].class)) {
        return (T) ("Bye " + ((MyFooBean)value).getName()).getBytes();
    }
    if (type.isAssignableFrom(Map.class)) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", ((MyFooBean)value).getName());
        return (T) map;
    }
    return null;
}
项目:Camel    文件:CamelJaxbFallbackConverterTest.java   
@Test
public void testConverter() throws Exception {
    TypeConverter converter = context.getTypeConverter();
    PersonType person = converter.convertTo(PersonType.class, "<Person><firstName>FOO</firstName><lastName>BAR</lastName></Person>");
    assertNotNull("Person should not be null ", person);
    assertEquals("Get the wrong first name ", "FOO", person.getFirstName());
    assertEquals("Get the wrong second name ", "BAR", person.getLastName());
    Exchange exchange = new DefaultExchange(context);
    exchange.setProperty(Exchange.CHARSET_NAME, "UTF-8");

    String value = converter.convertTo(String.class, exchange, person);
    assertTrue("Should get a right marshalled string", value.indexOf("<lastName>BAR</lastName>") > 0);

    byte[] buffers = "<Person><firstName>FOO</firstName><lastName>BAR\u0008</lastName></Person>".getBytes("UTF-8");
    InputStream is = new ByteArrayInputStream(buffers);
    try {
        converter.convertTo(PersonType.class, exchange, is);
        fail("Should have thrown exception");
    } catch (TypeConversionException e) {
        // expected
    }
}
项目:Camel    文件:RabbitMQMessagePublisher.java   
public void publish() throws IOException {
    AMQP.BasicProperties properties;
    byte[] body;
    try {
        // To maintain backwards compatibility try the TypeConverter (The DefaultTypeConverter seems to only work on Strings)
        body = camelExchange.getContext().getTypeConverter().mandatoryConvertTo(byte[].class, camelExchange, message.getBody());

        properties = endpoint.getMessageConverter().buildProperties(camelExchange).build();
    } catch (NoTypeConversionAvailableException | TypeConversionException e) {
        if (message.getBody() instanceof Serializable) {
            // Add the header so the reply processor knows to de-serialize it
            message.getHeaders().put(RabbitMQEndpoint.SERIALIZE_HEADER, true);
            properties = endpoint.getMessageConverter().buildProperties(camelExchange).build();
            body = serializeBodyFrom(message);
        } else if (message.getBody() == null) {
            properties = endpoint.getMessageConverter().buildProperties(camelExchange).build();
            body = null;
        } else {
            LOG.warn("Could not convert {} to byte[]", message.getBody());
            throw new RuntimeCamelException(e);
        }
    }

    publishToRabbitMQ(properties, body);
}
项目:Camel    文件:TypeConverterSupport.java   
@Override
public <T> T mandatoryConvertTo(Class<T> type, Object value) throws TypeConversionException, NoTypeConversionAvailableException {
    T t = convertTo(type, null, value);
    if (t == null) {
        throw new NoTypeConversionAvailableException(value, type);
    } else {
        return t;
    }
}
项目:Camel    文件:TypeConverterSupport.java   
@Override
public <T> T mandatoryConvertTo(Class<T> type, Exchange exchange, Object value) throws TypeConversionException, NoTypeConversionAvailableException {
    T t = convertTo(type, exchange, value);
    if (t == null) {
        throw new NoTypeConversionAvailableException(value, type);
    } else {
        return t;
    }
}
项目:Camel    文件:FlexibleAggregationStrategy.java   
@Override
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
    Exchange exchange = oldExchange;
    if (exchange == null) {
        exchange = ExchangeHelper.createCorrelatedCopy(newExchange, true);
        injector.prepareAggregationExchange(exchange);
    }

    // 1. Apply the condition and reject the aggregation if unmatched
    if (conditionPredicate != null && !conditionPredicate.matches(newExchange)) {
        LOG.trace("Dropped exchange {} from aggregation as predicate {} was not matched", newExchange, conditionPredicate);
        return exchange;
    }

    // 2. Pick the appropriate element of the incoming message, casting it to the specified class
    //    If null, act accordingly based on storeNulls
    E picked = null;
    try {
        picked = pickExpression.evaluate(newExchange, castAs);
    } catch (TypeConversionException exception) {
        if (!ignoreInvalidCasts) {
            throw exception;
        }
    }

    if (picked == null && !storeNulls) {
        LOG.trace("Dropped exchange {} from aggregation as pick expression returned null and storing nulls is not enabled", newExchange);
        return exchange;
    }

    if (collectionType == null) {
        injectAsRawValue(exchange, picked);
    } else {
        injectAsCollection(exchange, picked);
    }

    return exchange;
}
项目:Camel    文件:ExchangeHelper.java   
/**
 * Converts the value to the given expected type or throws an exception
 *
 * @return the converted value
 * @throws TypeConversionException is thrown if error during type conversion
 * @throws NoTypeConversionAvailableException} if no type converters exists to convert to the given type
 */
public static <T> T convertToMandatoryType(Exchange exchange, Class<T> type, Object value)
    throws TypeConversionException, NoTypeConversionAvailableException {
    CamelContext camelContext = exchange.getContext();
    ObjectHelper.notNull(camelContext, "CamelContext of Exchange");
    TypeConverter converter = camelContext.getTypeConverter();
    if (converter != null) {
        return converter.mandatoryConvertTo(type, exchange, value);
    }
    throw new NoTypeConversionAvailableException(value, type);
}
项目:Camel    文件:ExchangeHelper.java   
/**
 * Converts the value to the given expected type
 *
 * @return the converted value
 * @throws org.apache.camel.TypeConversionException is thrown if error during type conversion
 */
public static <T> T convertToType(Exchange exchange, Class<T> type, Object value) throws TypeConversionException {
    CamelContext camelContext = exchange.getContext();
    ObjectHelper.notNull(camelContext, "CamelContext of Exchange");
    TypeConverter converter = camelContext.getTypeConverter();
    if (converter != null) {
        return converter.convertTo(type, exchange, value);
    }
    return null;
}
项目:Camel    文件:BaseTypeConverterRegistry.java   
@SuppressWarnings("unchecked")
@Override
public <T> T mandatoryConvertTo(Class<T> type, Exchange exchange, Object value) throws NoTypeConversionAvailableException {
    if (!isRunAllowed()) {
        throw new IllegalStateException(this + " is not started");
    }

    Object answer;
    try {
        answer = doConvertTo(type, exchange, value, false);
    } catch (Exception e) {
        if (statistics.isStatisticsEnabled()) {
            failedCounter.incrementAndGet();
        }
        // error occurred during type conversion
        if (e instanceof TypeConversionException) {
            throw (TypeConversionException) e;
        } else {
            throw createTypeConversionException(exchange, type, value, e);
        }
    }
    if (answer == Void.TYPE || value == null) {
        if (statistics.isStatisticsEnabled()) {
            missCounter.incrementAndGet();
        }
        // Could not find suitable conversion
        throw new NoTypeConversionAvailableException(value, type);
    } else {
        if (statistics.isStatisticsEnabled()) {
            hitCounter.incrementAndGet();
        }
        return (T) answer;
    }
}
项目:Camel    文件:BaseTypeConverterRegistry.java   
protected TypeConversionException createTypeConversionException(Exchange exchange, Class<?> type, Object value, Throwable cause) {
    Object body;
    // extract the body for logging which allows to limit the message body in the exception/stacktrace
    // and also can be used to turn off logging sensitive message data
    if (exchange != null) {
        body = MessageHelper.extractValueForLogging(value, exchange.getIn());
    } else {
        body = value;
    }
    return new TypeConversionException(body, type, cause);
}
项目:Camel    文件:FutureTypeConverter.java   
@Override
public <T> T convertTo(Class<T> type, Exchange exchange, Object value) {
    try {
        return doConvertTo(type, exchange, value);
    } catch (Exception e) {
        throw new TypeConversionException(value, type, e);
    }
}
项目:Camel    文件:ConverterTest.java   
public void testStringToChar() throws Exception {
    char ch = converter.convertTo(char.class, "A");
    assertEquals('A', ch);

    ch = converter.convertTo(char.class, " ");
    assertEquals(' ', ch);

    try {
        converter.mandatoryConvertTo(char.class, "ABC");
        fail("Should have thrown an exception");
    } catch (TypeConversionException e) {
        assertEquals("java.lang.IllegalArgumentException: String must have exactly a length of 1: ABC", e.getCause().getMessage());
    }
}
项目:Camel    文件:EnumConverterTest.java   
public void testMandatoryConvertFailed() throws Exception {
    try {
        context.getTypeConverter().mandatoryConvertTo(LoggingLevel.class, "XXX");
        fail("Should have thrown an exception");
    } catch (TypeConversionException e) {
        // expected
    }
}
项目:Camel    文件:DurationConverterTest.java   
public void testToMillisOverflow() throws Exception {
    Duration duration = Duration.parse("P60000000000000D");
    try {
        context.getTypeConverter().convertTo(long.class, duration);
        fail("Should throw exception");
    } catch (TypeConversionException e) {
        assertIsInstanceOf(ArithmeticException.class, e.getCause().getCause());
    }
}
项目:Camel    文件:XPathFeatureTest.java   
public void testXPath() throws Exception {
    // Set this feature will enable the external general entities
    System.setProperty(DOM_BUILDER_FACTORY_FEATURE + ":"
        + "http://xml.org/sax/features/external-general-entities", "true");
    try {
        xpath("/").stringResult().evaluate(createExchange(XML_DATA));
        fail("Expect an Exception here");
    } catch (TypeConversionException ex) {
        assertTrue("Get a wrong exception cause.", ex.getCause() instanceof RuntimeCamelException);
        assertTrue("Get a wrong exception cause.", ex.getCause().getCause() instanceof FileNotFoundException);
    } finally {
        System.clearProperty(DOM_BUILDER_FACTORY_FEATURE + ":"
            + "http://xml.org/sax/features/external-general-entities");
    }
}
项目:Camel    文件:XPathFeatureTest.java   
public void testXPathResultOnInvalidData() throws Exception {
    try {
        xpath("/").stringResult().evaluate(createExchange(XML_DATA_INVALID));
        fail("Expect an Exception here");
    } catch (TypeConversionException ex) {
        assertTrue("Get a wrong exception cause.", ex.getCause() instanceof RuntimeCamelException);
        assertTrue("Get a wrong exception cause.", ex.getCause().getCause() instanceof SAXParseException);
    }
}
项目:Camel    文件:BeanParameterInvalidValueTest.java   
public void testBeanParameterInvalidValueA() throws Exception {
    getMockEndpoint("mock:result").expectedMessageCount(0);

    try {
        template.sendBody("direct:a", "World");
        fail("Should have thrown exception");
    } catch (CamelExecutionException e) {
        TypeConversionException cause = assertIsInstanceOf(TypeConversionException.class, e.getCause().getCause());
        assertEquals(String.class, cause.getFromType());
        assertEquals(int.class, cause.getToType());
        assertEquals("A", cause.getValue());
    }

    assertMockEndpointsSatisfied();
}
项目:Camel    文件:BeanParameterInvalidValueTest.java   
public void testBeanParameterInvalidValueB() throws Exception {
    getMockEndpoint("mock:result").expectedMessageCount(0);

    try {
        template.sendBody("direct:b", "World");
        fail("Should have thrown exception");
    } catch (CamelExecutionException e) {
        TypeConversionException cause = assertIsInstanceOf(TypeConversionException.class, e.getCause().getCause());
        assertEquals(String.class, cause.getFromType());
        assertEquals(int.class, cause.getToType());
        assertEquals("true", cause.getValue());
    }

    assertMockEndpointsSatisfied();
}
项目:Camel    文件:CachedCxfPayloadTest.java   
@Test
public void testCachedCxfPayloadSAXSource() throws TypeConversionException, NoTypeConversionAvailableException, IOException {
    SAXSource source = context.getTypeConverter().mandatoryConvertTo(SAXSource.class, PAYLOAD);
    // this conversion uses org.apache.camel.converter.jaxp.XmlConverter.toDOMNodeFromSAX which uses Transformer
    // to convert SAXSource to DOM. This conversion preserves the content but loses its original representation.
    doTest(source, PAYLOAD_AMPED);
}
项目:Camel    文件:FallbackTypeConverter.java   
public <T> T convertTo(Class<T> type, Exchange exchange, Object value) {
    if (BeanInvocation.class.isAssignableFrom(type) || Processor.class.isAssignableFrom(type)) {
        // JAXB cannot convert to a BeanInvocation / Processor, so we need to indicate this
        // to avoid Camel trying to do this when using beans with JAXB payloads
        return null;
    }

    try {
        if (isJaxbType(type)) {
            return unmarshall(type, exchange, value);
        }
        if (value != null && isNotStreamCacheType(type)) {
            if (hasXmlRootElement(value.getClass())) {
                return marshall(type, exchange, value, null);
            }
            if (isObjectFactory()) {
                CamelContext context = exchange != null ? exchange.getContext() : camelContext;
                Method objectFactoryMethod = JaxbHelper.getJaxbElementFactoryMethod(context, value.getClass());
                if (objectFactoryMethod != null) {
                    return marshall(type, exchange, value, objectFactoryMethod);
                }
            }
        }
    } catch (Exception e) {
        throw new TypeConversionException(value, type, e);
    }

    // should return null if didn't even try to convert at all or for whatever reason the conversion is failed
    return null;
}
项目:Camel    文件:JAXBConvertTest.java   
@Test
public void testStreamShouldBeClosedEvenForException() throws Exception {
    String data = "<errorOrder name='foo' amount='123.45' price='2.22'/>";
    InputStream is = new ByteArrayInputStream(data.getBytes());

    try {
        converter.convertTo(PurchaseOrder.class, is);
        fail("Should have thrown exception");
    } catch (TypeConversionException e) {
        // expected
    }
    assertEquals(-1, is.read());
}
项目:Camel    文件:XmlRpcConverterTest.java   
@Test(expected = TypeConversionException.class)
public void testToXmlRpcRequestWithoutOperationName() throws Exception {
    CamelContext context = new DefaultCamelContext();
    Exchange exchange = new DefaultExchange(context);

    exchange.getIn().setBody(new Object[] {"me", "you"});
    exchange.getIn().getBody(XmlRpcRequest.class);
    fail("Expect the exception is throw");

}
项目:Camel    文件:SpringTypeConverter.java   
@Override
public <T> T convertTo(Class<T> type, Exchange exchange, Object value) throws TypeConversionException {
    // do not attempt to convert Camel types
    if (type.getCanonicalName().startsWith("org.apache")) {
        return null;
    }

    for (ConversionService conversionService : conversionServices) {
        if (conversionService.canConvert(value.getClass(), type)) {
            return conversionService.convert(value, type);
        }
    }
    return null;
}
项目:Camel    文件:DozerTypeConverter.java   
@Override
public <T> T convertTo(Class<T> type, Exchange exchange, Object value) throws TypeConversionException {

    CamelContext context = exchange != null ? exchange.getContext() : null;
    ClassLoader appcl = context != null ? context.getApplicationContextClassLoader() : null;

    T result;

    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    try {
        if (appcl != null && appcl != tccl) {
            LOG.debug("Switching TCCL to: {}", appcl);
            Thread.currentThread().setContextClassLoader(appcl);
        }

        // find the map id, so we can provide that when trying to map from source to destination
        String mapId = null;
        if (value != null) {
            Class<?> sourceType = value.getClass();
            ClassMappingMetadata metadata = getClassMappingMetadata(sourceType, type);
            if (metadata != null) {
                mapId = metadata.getMapId();
            }
        }

        result = mapper.map(value, type, mapId);

    } finally {
        if (appcl != null && appcl != tccl) {
            Thread.currentThread().setContextClassLoader(tccl);
            LOG.debug("Restored TCCL to: {}", tccl);
        }
    }

    return result;
}
项目:switchyard    文件:OperationSelectorTest.java   
@SuppressWarnings("unchecked")
@Override
public <T> T convertTo(Class<T> type, Exchange exchange, Object value)
        throws TypeConversionException {
    BigEndianHeapChannelBuffer buffer = BigEndianHeapChannelBuffer.class.cast(value);
    return (T) new String(buffer.array());
}
项目:mdpnp    文件:QosConfigTest.java   
@Test
public void testSetVisibleInnerFieldBadValue() throws Exception {
    SubClass dummy = new SubClass();

    // NOTE: we pass a *non-numeric* value as String for a field of type "int"
    Assert.assertEquals(2000, dummy.outer.inner.int_value);
    try {
        RtiHelper.setConfigurationField(context, dummy, "outer.inner.int_value", "non-integer");
    } catch (TypeConversionException e) {
        // expected
    }
}
项目:morc    文件:XmlTestResource.java   
/**
 * @param exchange The exchange containing the XML document to validate
 * @return true if the input and test resource are similar using XMLUnit's Diff.similar()
 */
public synchronized boolean matches(Exchange exchange) {
    Document value;
    try {
        value = exchange.getIn().getBody(Document.class);
    } catch (TypeConversionException e) {
        logger.warn("Error attempting to convert XML to a Document", e);
        return false;
    }
    return value != null && validate(value);
}
项目:morc    文件:JsonTestResource.java   
/**
 * @param exchange The exchange containing the JSON string to validate
 * @return true if the Json trees match (uses the Jackson ObjectMapper to unmarshal the string and compare using Java equality)
 */
public synchronized boolean matches(Exchange exchange) {
    String value;
    try {
        value = exchange.getIn().getBody(String.class);
    } catch (TypeConversionException e) {
        logger.warn("Error attempting to convert JSON to a String", e);
        return false;
    }
    return value != null && validate(value);
}
项目:morc    文件:PlainTextTestResource.java   
/**
 * @param exchange The exchange containing the text string to validate against
 * @return true if the input String is the same as the test resource using Java String equality
 */
public synchronized boolean matches(Exchange exchange) {
    String value;
    try {
        value = exchange.getIn().getBody(String.class);
    } catch (TypeConversionException e) {
        logger.warn("Error attempting to convert exchange to a String", e);
        return false;
    }
    return value != null && validate(value);
}
项目:Camel    文件:TypeConverterSupport.java   
@Override
public <T> T convertTo(Class<T> type, Object value) throws TypeConversionException {
    return convertTo(type, null, value);
}
项目:Camel    文件:BaseTypeConverterRegistry.java   
@SuppressWarnings("unchecked")
@Override
public <T> T convertTo(Class<T> type, Exchange exchange, Object value) {
    if (!isRunAllowed()) {
        throw new IllegalStateException(this + " is not started");
    }

    Object answer;
    try {
        answer = doConvertTo(type, exchange, value, false);
    } catch (Exception e) {
        if (statistics.isStatisticsEnabled()) {
            failedCounter.incrementAndGet();
        }
        // if its a ExecutionException then we have rethrow it as its not due to failed conversion
        // this is special for FutureTypeConverter
        boolean execution = ObjectHelper.getException(ExecutionException.class, e) != null
                || ObjectHelper.getException(CamelExecutionException.class, e) != null;
        if (execution) {
            throw ObjectHelper.wrapCamelExecutionException(exchange, e);
        }

        // error occurred during type conversion
        if (e instanceof TypeConversionException) {
            throw (TypeConversionException) e;
        } else {
            throw createTypeConversionException(exchange, type, value, e);
        }
    }
    if (answer == Void.TYPE) {
        if (statistics.isStatisticsEnabled()) {
            missCounter.incrementAndGet();
        }
        // Could not find suitable conversion
        return null;
    } else {
        if (statistics.isStatisticsEnabled()) {
            hitCounter.incrementAndGet();
        }
        return (T) answer;
    }
}
项目:Camel    文件:CachedCxfPayloadTest.java   
@Test
public void testCachedCxfPayloadStAXSource() throws TypeConversionException, NoTypeConversionAvailableException, IOException {
    StAXSource source = context.getTypeConverter().mandatoryConvertTo(StAXSource.class, PAYLOAD);
    doTest(source, PAYLOAD);
}
项目:Camel    文件:CachedCxfPayloadTest.java   
@Test
public void testCachedCxfPayloadStaxSource() throws TypeConversionException, NoTypeConversionAvailableException, IOException {
    XMLStreamReader streamReader = StaxUtils.createXMLStreamReader(new StreamSource(new StringReader(PAYLOAD)));
    StaxSource source = new StaxSource(streamReader);
    doTest(source, PAYLOAD);
}
项目:Camel    文件:CachedCxfPayloadTest.java   
@Test
public void testCachedCxfPayloadDOMSource() throws TypeConversionException, NoTypeConversionAvailableException, IOException {
    DOMSource source = context.getTypeConverter().mandatoryConvertTo(DOMSource.class, PAYLOAD);
    doTest(source, PAYLOAD);
}
项目:Camel    文件:CachedCxfPayloadTest.java   
@Test
public void testCachedCxfPayloadStreamSource() throws TypeConversionException, NoTypeConversionAvailableException, IOException {
    StreamSource source = context.getTypeConverter().mandatoryConvertTo(StreamSource.class, PAYLOAD);
    doTest(source, PAYLOAD);
}
项目:Camel    文件:FallbackTypeConverter.java   
protected <T> T marshall(Class<T> type, Exchange exchange, Object value, Method objectFactoryMethod)
    throws JAXBException, XMLStreamException, FactoryConfigurationError, TypeConversionException {
    LOG.trace("Marshal from value {} to type {}", value, type);

    T answer = null;
    if (parentTypeConverter != null) {
        // lets convert the object to a JAXB source and try convert that to
        // the required source
        JAXBContext context = createContext(value.getClass());
        // must create a new instance of marshaller as its not thread safe
        Marshaller marshaller = context.createMarshaller();
        Writer buffer = new StringWriter();

        if (isPrettyPrint()) {
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        }
        if (exchange != null && exchange.getProperty(Exchange.CHARSET_NAME, String.class) != null) {
            marshaller.setProperty(Marshaller.JAXB_ENCODING, exchange.getProperty(Exchange.CHARSET_NAME, String.class));
        }
        Object toMarshall = value;
        if (objectFactoryMethod != null) {
            try {
                Object instance = objectFactoryMethod.getDeclaringClass().newInstance();
                if (instance != null) {
                    toMarshall = objectFactoryMethod.invoke(instance, value);
                }
            } catch (Exception e) {
                LOG.debug("Unable to create JAXBElement object for type " + value.getClass() + " due to " + e.getMessage(), e);
            }
        }
        if (needFiltering(exchange)) {
            XMLStreamWriter writer = parentTypeConverter.convertTo(XMLStreamWriter.class, buffer);
            FilteringXmlStreamWriter filteringWriter = new FilteringXmlStreamWriter(writer);
            marshaller.marshal(toMarshall, filteringWriter);
        } else {
            marshaller.marshal(toMarshall, buffer);
        }
        // we need to pass the exchange
        answer = parentTypeConverter.convertTo(type, exchange, buffer.toString());
    }
    return answer;
}
项目:Camel    文件:ExchangeHelper.java   
/**
 * Gets the mandatory inbound header of the correct type
 *
 * @param exchange      the exchange
 * @param headerName    the header name
 * @param type          the type
 * @return the header value
 * @throws TypeConversionException is thrown if error during type conversion
 * @throws NoSuchHeaderException is thrown if no headers exists
 */
public static <T> T getMandatoryHeader(Exchange exchange, String headerName, Class<T> type) throws TypeConversionException, NoSuchHeaderException {
    T answer = exchange.getIn().getHeader(headerName, type);
    if (answer == null) {
        throw new NoSuchHeaderException(exchange, headerName, type);
    }
    return answer;
}