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

项目:Camel    文件:IntrospectionSupport.java   
private static Object convert(TypeConverter typeConverter, Class<?> type, Object value)
    throws URISyntaxException, NoTypeConversionAvailableException {
    if (typeConverter != null) {
        return typeConverter.mandatoryConvertTo(type, value);
    }
    if (type == URI.class) {
        return new URI(value.toString());
    }
    PropertyEditor editor = PropertyEditorManager.findEditor(type);
    if (editor != null) {
        // property editor is not thread safe, so we need to lock
        Object answer;
        synchronized (LOCK) {
            editor.setAsText(value.toString());
            answer = editor.getValue();
        }
        return answer;
    }
    return null;
}
项目:Camel    文件:GenericFileConverter.java   
@Converter
public static InputStream genericFileToInputStream(GenericFile<?> file, Exchange exchange) throws IOException, NoTypeConversionAvailableException {
    if (file.getFile() instanceof File) {
        // prefer to use a file input stream if its a java.io.File
        File f = (File) file.getFile();
        // the file must exists
        if (f.exists()) {
            // read the file using the specified charset
            String charset = file.getCharset();
            if (charset != null) {
                LOG.debug("Read file {} with charset {}", f, file.getCharset());
            } else {
                LOG.debug("Read file {} (no charset)", f);
            }
            return IOConverter.toInputStream(f, charset);
        }
    }
    if (exchange != null) {
        // otherwise ensure the body is loaded as we want the input stream of the body
        file.getBinding().loadContent(exchange, file);
        return exchange.getContext().getTypeConverter().convertTo(InputStream.class, exchange, file.getBody());
    } else {
        // should revert to fallback converter if we don't have an exchange
        return null;
    }
}
项目:Camel    文件:GenericFileConverter.java   
@Converter
public static String genericFileToString(GenericFile<?> file, Exchange exchange) throws IOException, NoTypeConversionAvailableException {
    // use reader first as it supports the file charset
    BufferedReader reader = genericFileToReader(file, exchange);
    if (reader != null) {
        return IOConverter.toString(reader);
    }
    if (exchange != null) {
        // otherwise ensure the body is loaded as we want the content of the body
        file.getBinding().loadContent(exchange, file);
        return exchange.getContext().getTypeConverter().convertTo(String.class, exchange, file.getBody());
    } else {
        // should revert to fallback converter if we don't have an exchange
        return null;
    }
}
项目:Camel    文件:GenericFileConverter.java   
@Converter
public static Serializable genericFileToSerializable(GenericFile<?> file, Exchange exchange) throws IOException, NoTypeConversionAvailableException {
    if (exchange != null) {
        // load the file using input stream
        InputStream is = genericFileToInputStream(file, exchange);
        if (is != null) {
            // need to double convert to convert correctly
            byte[] data = exchange.getContext().getTypeConverter().convertTo(byte[].class, exchange, is);
            if (data != null) {
                return exchange.getContext().getTypeConverter().convertTo(Serializable.class, exchange, data);
            }
        }
    }
    // should revert to fallback converter if we don't have an exchange
    return null;
}
项目:Camel    文件:GenericFileConverter.java   
private static BufferedReader genericFileToReader(GenericFile<?> file, Exchange exchange) throws IOException, NoTypeConversionAvailableException {
    if (file.getFile() instanceof File) {
        // prefer to use a file input stream if its a java.io.File
        File f = (File) file.getFile();
        // the file must exists
        if (!f.exists()) {
            return null;
        }
        // and use the charset if the file was explicit configured with a charset
        String charset = file.getCharset();
        if (charset != null) {
            LOG.debug("Read file {} with charset {}", f, file.getCharset());
            return IOConverter.toReader(f, charset);
        } else {
            LOG.debug("Read file {} (no charset)", f);
            return IOConverter.toReader(f, exchange);
        }
    }
    return null;
}
项目:Camel    文件:XPathLanguageSingleNodeListTest.java   
/**
 * Regression test to ensure that a NodeList of length > 1 is not processed by the new converters.
 * @throws Exception
 */
@Test
public void testMultipleNodeList() throws Exception {
    getMockEndpoint("mock:found").expectedMessageCount(0);
    getMockEndpoint("mock:found").setResultWaitTime(500);
    getMockEndpoint("mock:notfound").expectedMessageCount(0);
    getMockEndpoint("mock:notfound").setResultWaitTime(500);

    try {
        template.requestBody("direct:doTest", XML_INPUT_MULTIPLE, String.class);
        fail("NoTypeConversionAvailableException expected");
    } catch (CamelExecutionException ex) {
        assertEquals(RuntimeCamelException.class, ex.getCause().getClass());
        assertEquals(NoTypeConversionAvailableException.class, ex.getCause().getCause().getClass());
    }

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

    // we send in a Date object which cannot be converted to XML so it should fail
    try {
        template.requestBody("direct:start", new Date());
        fail("Should have thrown an exception");
    } catch (CamelExecutionException e) {
        NoTypeConversionAvailableException ntae = assertIsInstanceOf(NoTypeConversionAvailableException.class, e.getCause().getCause());
        assertEquals(Date.class, ntae.getFromType());
        assertEquals(Document.class, ntae.getToType());
        assertNotNull(ntae.getValue());
        assertNotNull(ntae.getMessage());
    }

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

    // we send in a bar string as header which cannot be converted to a number so it should fail
    try {
        template.requestBodyAndHeader("direct:start", "Hello World", "foo", 555);
        fail("Should have thrown an exception");
    } catch (CamelExecutionException e) {
        ParameterBindingException pbe = assertIsInstanceOf(ParameterBindingException.class, e.getCause());
        assertEquals(1, pbe.getIndex());
        assertTrue(pbe.getMethod().getName().contains("hello"));
        assertEquals(555, pbe.getParameterValue());

        NoTypeConversionAvailableException ntae = assertIsInstanceOf(NoTypeConversionAvailableException.class, e.getCause().getCause());
        assertEquals(Integer.class, ntae.getFromType());
        assertEquals(Document.class, ntae.getToType());
        assertEquals(555, ntae.getValue());
        assertNotNull(ntae.getMessage());
    }

    assertMockEndpointsSatisfied();
}
项目:Camel    文件:BeanWithHeadersAndBodyInject2Test.java   
public void testCannotBindToParameter() throws Exception {
    // Create hashmap for testing purpose
    users.put("charles", new User("Charles", "43"));
    users.put("claus", new User("Claus", "33"));

    Exchange out = template.send("direct:in", new Processor() {
        public void process(Exchange exchange) throws Exception {
            exchange.setProperty("p1", "abc");
            exchange.setProperty("p2", 123);

            Message in = exchange.getIn();
            in.setHeader("users", users); // add users hashmap
            in.setBody("TheBody");
        }
    });

    assertTrue("Should fail", out.isFailed());
    assertIsInstanceOf(RuntimeCamelException.class, out.getException());
    assertIsInstanceOf(NoTypeConversionAvailableException.class, out.getException().getCause());
}
项目:Camel    文件:BeanOverloadedMethodFQNTest.java   
public void testOrderNoFQNUnknown() throws Exception {
    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
                .bean(MyBean.class, "order(Unknown)")
                .to("mock:result");

        }
    });
    context.start();

    try {
        template.sendBody("direct:start", new MyOrder());
        fail("Should have thrown an exception");
    } catch (CamelExecutionException e) {
        NoTypeConversionAvailableException cause = assertIsInstanceOf(NoTypeConversionAvailableException.class, e.getCause().getCause());
        assertEquals("Unknown", cause.getValue());
    }
}
项目:Camel    文件:BeanOverloadedMethodFQNTest.java   
public void testOrderFQNUnknown() throws Exception {
    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
                .bean(MyBean.class, "order(org.apache.camel.component.bean.BeanOverloadedMethodFQNTest$Unknown)")
                .to("mock:result");

        }
    });
    context.start();

    try {
        template.sendBody("direct:start", new MyOrder());
        fail("Should have thrown an exception");
    } catch (CamelExecutionException e) {
        NoTypeConversionAvailableException cause = assertIsInstanceOf(NoTypeConversionAvailableException.class, e.getCause().getCause());
        assertEquals("org.apache.camel.component.bean.BeanOverloadedMethodFQNTest$Unknown", cause.getValue());
    }
}
项目:Camel    文件:Marshaller.java   
/**
 * Writes the given row.
 *
 * @param exchange exchange to use (for type conversion)
 * @param row      row to write
 * @param writer   uniVocity writer to use
 * @throws NoTypeConversionAvailableException when it's not possible to convert the row as map.
 */
private void writeRow(Exchange exchange, Object row, W writer) throws NoTypeConversionAvailableException {
    Map<?, ?> map = convertToMandatoryType(exchange, Map.class, row);
    if (adaptHeaders) {
        for (Object key : map.keySet()) {
            headers.add(convertToMandatoryType(exchange, String.class, key));
        }
    }

    Object[] values = new Object[headers.size()];
    int index = 0;
    for (String header : headers) {
        values[index++] = map.get(header);
    }
    writer.writeRow(values);
}
项目:Camel    文件:NettyHelper.java   
/**
 * Gets the string body to be used when sending with the textline codec.
 *
 * @param body                 the current body
 * @param exchange             the exchange
 * @param delimiter            the textline delimiter
 * @param autoAppendDelimiter  whether absent delimiter should be auto appended
 * @return the string body to send
 * @throws NoTypeConversionAvailableException is thrown if the current body could not be converted to a String type
 */
public static String getTextlineBody(Object body, Exchange exchange, TextLineDelimiter delimiter, boolean autoAppendDelimiter) throws NoTypeConversionAvailableException {
    String s = exchange.getContext().getTypeConverter().mandatoryConvertTo(String.class, exchange, body);

    // auto append delimiter if missing?
    if (autoAppendDelimiter) {
        if (TextLineDelimiter.LINE.equals(delimiter)) {
            // line delimiter so ensure it ends with newline
            if (!s.endsWith("\n")) {
                LOG.trace("Auto appending missing newline delimiter to body");
                s = s + "\n";
            }
        } else {
            // null delimiter so ensure it ends with null
            if (!s.endsWith("\u0000")) {
                LOG.trace("Auto appending missing null delimiter to body");
                s = s + "\u0000";
            }
        }
    }

    return s;
}
项目:Camel    文件:MailConverters.java   
private static long extractOffset(String now, TypeConverter typeConverter) throws NoTypeConversionAvailableException {
    Matcher matcher = NOW_PATTERN.matcher(now);
    if (matcher.matches()) {
        String op = matcher.group(1);
        String remainder = matcher.group(2);

        // convert remainder to a time millis (eg we have a String -> long converter that supports
        // syntax with hours, days, minutes: eg 5h30m for 5 hours and 30 minutes).
        long offset = typeConverter.mandatoryConvertTo(long.class, remainder);

        if ("+".equals(op)) {
            return offset;
        } else {
            return -1 * offset;
        }
    }

    return 0;
}
项目:Camel    文件:NettyHelper.java   
/**
 * Gets the string body to be used when sending with the textline codec.
 *
 * @param body                 the current body
 * @param exchange             the exchange
 * @param delimiter            the textline delimiter
 * @param autoAppendDelimiter  whether absent delimiter should be auto appended
 * @return the string body to send
 * @throws NoTypeConversionAvailableException is thrown if the current body could not be converted to a String type
 */
public static String getTextlineBody(Object body, Exchange exchange, TextLineDelimiter delimiter, boolean autoAppendDelimiter) throws NoTypeConversionAvailableException {
    String s = exchange.getContext().getTypeConverter().mandatoryConvertTo(String.class, exchange, body);

    // auto append delimiter if missing?
    if (autoAppendDelimiter) {
        if (TextLineDelimiter.LINE.equals(delimiter)) {
            // line delimiter so ensure it ends with newline
            if (!s.endsWith("\n")) {
                LOG.trace("Auto appending missing newline delimiter to body");
                s = s + "\n";
            }
        } else {
            // null delimiter so ensure it ends with null
            if (!s.endsWith("\u0000")) {
                LOG.trace("Auto appending missing null delimiter to body");
                s = s + "\u0000";
            }
        }
    }

    return s;
}
项目: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-c24io    文件:FallbackTypeConverter.java   
protected <T> T marshall(Class<T> type, ComplexDataObject dataObject, Exchange exchange) throws IOException {
    if (parentTypeConverter != null) {
        // TODO allow configuration to determine the sink from the Exchange

        Sink sink = getSink(dataObject, exchange);

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        sink.setOutputStream(buffer);
        sink.writeObject(dataObject);

        byte[] data = buffer.toByteArray();

        try {
            return parentTypeConverter.mandatoryConvertTo(type, data);
        } catch (NoTypeConversionAvailableException e) {
            return null;
        }
    }

    return null;
}
项目:syndesis    文件:FunctionHandler.java   
private String asBeanParameter(TypeConverter converter, Map.Entry<String, Object> entry) {
    try {
        return "bean." + entry.getKey() + "=" + converter.mandatoryConvertTo(String.class, entry.getValue());
    } catch (NoTypeConversionAvailableException e) {
        throw new IllegalStateException(e);
    }
}
项目:syndesis    文件:SqlStartConnectorComponent.java   
private <T> void consumeOption(String name, Class<T> type, Consumer<T> consumer) throws NoTypeConversionAvailableException {
    final TypeConverter converter = getCamelContext().getTypeConverter();
    final Object val = getOptions().get(name);
    final T result = converter.mandatoryConvertTo(type, val);

    consumer.accept(result);

    LOGGER.debug("Consume option {}", name);
    getOptions().remove(name);
}
项目:syndesis    文件:SqlConnectorComponent.java   
private <T> void consumeOption(String name, Class<T> type, Consumer<T> consumer) throws NoTypeConversionAvailableException {
    final TypeConverter converter = getCamelContext().getTypeConverter();
    final Object val = getOptions().get(name);
    final T result = converter.mandatoryConvertTo(type, val);

    consumer.accept(result);

    LOGGER.debug("Consume option {}", name);
    getOptions().remove(name);
}
项目:syndesis    文件:SqlStoredConnectorComponent.java   
private <T> void consumeOption(String name, Class<T> type, Consumer<T> consumer) throws NoTypeConversionAvailableException {
    final TypeConverter converter = getCamelContext().getTypeConverter();
    final Object val = getOptions().get(name);
    final T result = converter.mandatoryConvertTo(type, val);

    consumer.accept(result);

    LOGGER.debug("Consume option {}", name);
    getOptions().remove(name);
}
项目:syndesis    文件:SqlStoredStartConnectorComponent.java   
private <T> void consumeOption(String name, Class<T> type, Consumer<T> consumer) throws NoTypeConversionAvailableException {
    final TypeConverter converter = getCamelContext().getTypeConverter();
    final Object val = getOptions().get(name);
    final T result = converter.mandatoryConvertTo(type, val);

    consumer.accept(result);

    LOGGER.debug("Consume option {}", name);
    getOptions().remove(name);
}
项目:syndesis    文件:ComponentProxyComponent.java   
/**
 * Gather all options to use when building the delegate uri.
 */
private Map<String, String> buildEndpointOptions(String remaining, Map<String, Object> parameters) throws URISyntaxException, NoTypeConversionAvailableException {
    final TypeConverter converter = getCamelContext().getTypeConverter();
    final Map<String, String> endpointOptions = new LinkedHashMap<>();

    // Extract options from options that are supposed to be set at the endpoint
    // level, those options can be overridden and extended using by the query
    // parameters.
    Collection<String> endpointProperties = definition.getEndpointProperties().keySet();
    for (String key : endpointProperties) {
        Object val = this.options.get(key);
        if (val != null) {
            doAddOption(endpointOptions, key, converter.mandatoryConvertTo(String.class, val));
        }
    }

    // options from query parameters
    for (Map.Entry<String, Object> entry : parameters.entrySet()) {
        if (entry.getValue() != null) {
            doAddOption(endpointOptions, entry.getKey(), converter.mandatoryConvertTo(String.class, entry.getValue()));
        }
    }

    // add extra options from remaining (context-path)
    if (remaining != null) {
        String targetUri = componentScheme + ":" + remaining;
        Map<String, String> extra = catalog.endpointProperties(targetUri);
        if (extra != null && !extra.isEmpty()) {
            extra.forEach((key, value) -> doAddOption(endpointOptions, key, value));
        }
    }

    return endpointOptions;
}
项目:syndesis-integration-runtime    文件:FunctionHandler.java   
private String asBeanParameter(TypeConverter converter, Map.Entry<String, Object> entry) {
    try {
        return "bean." + entry.getKey() + "=" + converter.mandatoryConvertTo(String.class, entry.getValue());
    } catch (NoTypeConversionAvailableException e) {
        throw new IllegalStateException(e);
    }
}
项目:camel-isds    文件:ISDSTestBase.java   
/**
 * Mark all messages read for given accountovmId
 *
 * @param login isds login
 * @param password isds password
 * @throws NoTypeConversionAvailableException
 */
public void markMessagesRead(String login, String password) throws NoTypeConversionAvailableException {
    Authentication auth = new BasicAuthentication(TEST_CONFIG, login, password);
    DataBoxManager manager = new DataBoxManager(TEST_CONFIG, auth);

    log.info("Marking meessages as downloaded for login {}", login);
    List<MessageEnvelope> envs = manager.getDataBoxMessagesService()
            .getListOfReceivedMessages(
                    new Date(0L), new Date(Long.MAX_VALUE),
                    context().getTypeConverter().mandatoryConvertTo(EnumSet.class, "!read"),
                    1, Integer.MAX_VALUE);
    envs.stream().forEach(env -> manager.getDataBoxMessagesService().markMessageAsDownloaded(env));
}
项目:camel-isds    文件:ISDSComponentTest.java   
@Test
public void recieveMessageInBody() throws InterruptedException, IOException, NoTypeConversionAvailableException, NoSuchAlgorithmException {

    byte[] originalContent = context().getTypeConverter().mandatoryConvertTo(byte[].class, this.getClass().getResourceAsStream(SAMPLE_PDF_PATH));

    Attachment sourceAttachment = new Attachment(SAMPLE_PDF_PATH.replace("/", ""), new ByteContent(originalContent));
    sourceAttachment.setMetaType("main");
    // send message from FO to OVM
    Message message = createMessage(getOvmId(), "FO->OVM at " + new Date(), sourceAttachment);
    Message response = senderFo.requestBody(message, Message.class);

    // assert we received message with given id
    mockEndpoint.expectedBodiesReceived(response);
    mockEndpoint.assertIsSatisfied(TimeUnit.MINUTES.toMillis(1));

    // assert attachment was stored to filesystem correctly
    Message received = mockEndpoint.getReceivedExchanges().get(0).getIn().getBody(Message.class);
    // assume we send one attachment in test messages
    Attachment a = received.getAttachments().get(0);
    System.out.println("received attachment: " + a);
    String name = a.getDescription();
    Path filePath = Paths.get("target", "atts-ovm", String.format("%s_%s", received.getEnvelope().getMessageID(), name));
    assertTrue("Attachment file should exist: " + filePath, Files.exists(filePath));

    assertMD5equals("Hash of original and received message attachment must be the same",
            this.getClass().getResourceAsStream(SAMPLE_PDF_PATH),
            Files.newInputStream(filePath));
}
项目:Camel    文件:BacklogDebugger.java   
public void setMessageHeaderOnBreakpoint(String nodeId, String headerName, Object value) throws NoTypeConversionAvailableException {
    SuspendedExchange se = suspendedBreakpoints.get(nodeId);
    if (se != null) {
        Class<?> oldType;
        if (se.getExchange().hasOut()) {
            oldType = se.getExchange().getOut().getHeader(headerName) != null ? se.getExchange().getOut().getHeader(headerName).getClass() : null;
        } else {
            oldType = se.getExchange().getIn().getHeader(headerName) != null ? se.getExchange().getIn().getHeader(headerName).getClass() : null;
        }
        setMessageHeaderOnBreakpoint(nodeId, headerName, value, oldType);
    }
}
项目:Camel    文件:SendDynamicProcessor.java   
protected static Endpoint resolveEndpoint(Exchange exchange, Object recipient) throws NoTypeConversionAvailableException {
    // trim strings as end users might have added spaces between separators
    if (recipient instanceof String) {
        recipient = ((String) recipient).trim();
    } else if (recipient instanceof Endpoint) {
        return (Endpoint) recipient;
    } else {
        // convert to a string type we can work with
        recipient = exchange.getContext().getTypeConverter().mandatoryConvertTo(String.class, exchange, recipient);
    }

    return ExchangeHelper.resolveEndpoint(exchange, recipient);
}
项目: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    文件:ManagedBacklogDebugger.java   
public void setMessageHeaderOnBreakpoint(String nodeId, String headerName, Object value) {
    try {
        backlogDebugger.setMessageHeaderOnBreakpoint(nodeId, headerName, value);
    } catch (NoTypeConversionAvailableException e) {
        throw ObjectHelper.wrapRuntimeCamelException(e);
    }
}
项目: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    文件: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    文件:UnaryExpression.java   
private Expression createIncExpression(final Expression leftExp) {
    return new Expression() {
        @Override
        public <T> T evaluate(Exchange exchange, Class<T> type) {
            Number num = leftExp.evaluate(exchange, Number.class);
            if (num != null) {
                long val = num.longValue();
                val++;

                // convert value back to same type as input as we want to preserve type
                Object left = leftExp.evaluate(exchange, Object.class);
                try {
                    left = exchange.getContext().getTypeConverter().mandatoryConvertTo(left.getClass(), exchange, val);
                } catch (NoTypeConversionAvailableException e) {
                    throw ObjectHelper.wrapRuntimeCamelException(e);
                }

                // and return the result
                return exchange.getContext().getTypeConverter().convertTo(type, left);
            }
            // cannot convert the expression as a number
            Exception cause = new CamelExchangeException("Cannot evaluate " + leftExp + " as a number", exchange);
            throw ObjectHelper.wrapRuntimeCamelException(cause);
        }

        @Override
        public String toString() {
            return left + operator.toString();
        }
    };
}
项目:Camel    文件:UnaryExpression.java   
private Expression createDecExpression(final Expression leftExp) {
    return new Expression() {
        @Override
        public <T> T evaluate(Exchange exchange, Class<T> type) {
            Number num = leftExp.evaluate(exchange, Number.class);
            if (num != null) {
                long val = num.longValue();
                val--;

                // convert value back to same type as input as we want to preserve type
                Object left = leftExp.evaluate(exchange, Object.class);
                try {
                    left = exchange.getContext().getTypeConverter().mandatoryConvertTo(left.getClass(), exchange, val);
                } catch (NoTypeConversionAvailableException e) {
                    throw ObjectHelper.wrapRuntimeCamelException(e);
                }

                // and return the result
                return exchange.getContext().getTypeConverter().convertTo(type, left);
            }
            // cannot convert the expression as a number
            Exception cause = new CamelExchangeException("Cannot evaluate " + leftExp + " as a number", exchange);
            throw ObjectHelper.wrapRuntimeCamelException(cause);
        }

        @Override
        public String toString() {
            return left + operator.toString();
        }
    };
}
项目:Camel    文件:XPathBuilder.java   
protected Object doGetDocument(Exchange exchange, Object body) throws Exception {
    if (body == null) {
        return null;
    }

    Object answer = null;

    Class<?> type = getDocumentType();
    Exception cause = null;
    if (type != null) {
        // try to get the body as the desired type
        try {
            answer = exchange.getContext().getTypeConverter().convertTo(type, exchange, body);
        } catch (Exception e) {
            // we want to store the caused exception, if we could not convert
            cause = e;
        }
    }

    if (type == null && answer == null) {
        // fallback to get the body as is
        answer = body;
    } else if (answer == null) {
        // there was a type, and we could not convert to it, then fail
        if (cause != null) {
            throw cause;
        } else {
            throw new NoTypeConversionAvailableException(body, type);
        }
    }

    return answer;
}
项目:Camel    文件:FileBinding.java   
public void loadContent(Exchange exchange, GenericFile<?> file) throws IOException {
    if (content == null) {
        try {
            content = exchange.getContext().getTypeConverter().mandatoryConvertTo(byte[].class, exchange, file);
        } catch (NoTypeConversionAvailableException e) {
            throw new IOException("Cannot load file content: " + file.getAbsoluteFilePath(), e);
        }
    }
}
项目:Camel    文件:MethodInfo.java   
/**
 * Evaluate using classic parameter binding using the pre compute expression
 */
private Object evaluateParameterBinding(Exchange exchange, Expression expression, int index, Class<?> parameterType) {
    Object answer = null;

    // use object first to avoid type conversion so we know if there is a value or not
    Object result = expression.evaluate(exchange, Object.class);
    if (result != null) {
        try {
            if (parameterType.isInstance(result)) {
                // optimize if the value is already the same type
                answer = result;
            } else {
                // we got a value now try to convert it to the expected type
                answer = exchange.getContext().getTypeConverter().mandatoryConvertTo(parameterType, result);
            }
            if (LOG.isTraceEnabled()) {
                LOG.trace("Parameter #{} evaluated as: {} type: ", new Object[]{index, answer, ObjectHelper.type(answer)});
            }
        } catch (NoTypeConversionAvailableException e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Cannot convert from type: {} to type: {} for parameter #{}", new Object[]{ObjectHelper.type(result), parameterType, index});
            }
            throw new ParameterBindingException(e, method, index, parameterType, result);
        }
    } else {
        LOG.trace("Parameter #{} evaluated as null", index);
    }

    return answer;
}
项目:Camel    文件:ConverterTest.java   
public void testMandatoryConvertTo() {
    CamelContext camel = new DefaultCamelContext();
    Exchange e = new DefaultExchange(camel);
    try {
        converter.mandatoryConvertTo(InputStream.class, e);
        fail("Expect exception here");
    } catch (Exception ex) {
        assertTrue("Expect to get a NoTypeConversionAvailableException here", ex instanceof NoTypeConversionAvailableException); 
    }
}
项目:Camel    文件:StaticFallbackConverterTest.java   
public void testStaticFallbackMandatoryFailed() throws Exception {
    Exchange exchange = new DefaultExchange(context);

    try {
        context.getTypeConverter().mandatoryConvertTo(Date.class, exchange, new Timestamp(0));
        fail("Should have thrown an exception");
    } catch (NoTypeConversionAvailableException e) {
        // expected
    }
}