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

项目:Camel    文件:HandleFaultInterceptor.java   
/**
 * Handles the fault message by converting it to an Exception
 */
protected void handleFault(Exchange exchange) {
    // Take the fault message out before we keep on going
    Message msg = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
    if (msg.isFault()) {
        final Object faultBody = msg.getBody();
        if (faultBody != null && exchange.getException() == null) {
            // remove fault as we are converting it to an exception
            if (exchange.hasOut()) {
                exchange.setOut(null);
            } else {
                exchange.setIn(null);
            }
            if (faultBody instanceof Throwable) {
                exchange.setException((Throwable) faultBody);
            } else {
                // wrap it in an exception
                String data = exchange.getContext().getTypeConverter().convertTo(String.class, exchange, faultBody);
                exchange.setException(new CamelException(data));
            }
        }
    }
}
项目:Camel    文件:SplitterTest.java   
public void testSplitterWithException() throws Exception {
    MockEndpoint resultEndpoint = getMockEndpoint("mock:result");
    resultEndpoint.expectedMessageCount(4);
    resultEndpoint.expectedHeaderReceived("foo", "bar");

    MockEndpoint failedEndpoint = getMockEndpoint("mock:failed");
    failedEndpoint.expectedMessageCount(1);
    failedEndpoint.expectedHeaderReceived("foo", "bar");

    Exchange result = template.request("direct:exception", new Processor() {
        public void process(Exchange exchange) {
            Message in = exchange.getIn();
            in.setBody("James,Guillaume,Hiram,Rob,Exception");
            in.setHeader("foo", "bar");
        }
    });

    assertTrue("The result exchange should have a camel exception", result.getException() instanceof CamelException);

    assertMockEndpointsSatisfied();
}
项目:Camel    文件:RedeliveryErrorHandlerLogHandledTest.java   
public void testRedeliveryErrorHandlerDoNotLogExhausted() throws Exception {
    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            errorHandler(defaultErrorHandler().logExhausted(false));

            from("direct:bar")
                .throwException(new CamelException("Camel rocks"));
        }
    });
    context.start();

    getMockEndpoint("mock:handled").expectedMessageCount(0);

    try {
        template.sendBody("direct:bar", "Hello World");
        fail("Should thrown an exception");
    } catch (CamelExecutionException e) {
        CamelException cause = assertIsInstanceOf(CamelException.class, e.getCause());
        assertEquals("Camel rocks", cause.getMessage());
    }

    assertMockEndpointsSatisfied();
}
项目:Camel    文件:RedeliveryErrorHandlerLogHandledTest.java   
public void testRedeliveryErrorHandlerLogExhaustedDefault() throws Exception {
    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            errorHandler(defaultErrorHandler());

            from("direct:bar")
                .throwException(new CamelException("Camel rocks"));
        }
    });
    context.start();

    getMockEndpoint("mock:handled").expectedMessageCount(0);

    try {
        template.sendBody("direct:bar", "Hello World");
        fail("Should thrown an exception");
    } catch (CamelExecutionException e) {
        CamelException cause = assertIsInstanceOf(CamelException.class, e.getCause());
        assertEquals("Camel rocks", cause.getMessage());
    }

    assertMockEndpointsSatisfied();
}
项目:Camel    文件:AggregatorAndOnExceptionTest.java   
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            errorHandler(deadLetterChannel("mock:error"));

            onException(CamelException.class).maximumRedeliveries(2);

            from("seda:start")
                .aggregate(header("id"),
                    new AggregationStrategy() {
                        public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
                            return newExchange;
                        }
                    }).completionSize(2).completionTimeout(500L)
                .to("mock:result");
        }
    };
}
项目:Camel    文件:AvroDataFormat.java   
protected Schema loadSchema(String className) throws CamelException, ClassNotFoundException {
    // must use same class loading procedure to ensure working in OSGi
    Class<?> instanceClass = camelContext.getClassResolver().resolveMandatoryClass(className);
    Class<?> genericContainer = camelContext.getClassResolver().resolveMandatoryClass(GENERIC_CONTAINER_CLASSNAME);

    if (genericContainer.isAssignableFrom(instanceClass)) {
        try {
            Method method = instanceClass.getMethod("getSchema");
            return (Schema) method.invoke(camelContext.getInjector().newInstance(instanceClass));
        } catch (Exception ex) {
            throw new CamelException("Error calling getSchema on " + instanceClass, ex);
        }
    } else {
        throw new CamelException("Class " + instanceClass + " must be instanceof " + GENERIC_CONTAINER_CLASSNAME);
    }
}
项目:Camel    文件:BulkApiProcessor.java   
private void processCreateBatch(final Exchange exchange, final AsyncCallback callback) throws SalesforceException {
    String jobId;
    // since request is in the body, use headers or endpoint params
    ContentType contentType = ContentType.fromValue(
            getParameter(CONTENT_TYPE, exchange, IGNORE_BODY, NOT_OPTIONAL));
    jobId = getParameter(JOB_ID, exchange, IGNORE_BODY, NOT_OPTIONAL);

    InputStream request;
    try {
        request = exchange.getIn().getMandatoryBody(InputStream.class);
    } catch (CamelException e) {
        String msg = "Error preparing batch request: " + e.getMessage();
        throw new SalesforceException(msg, e);
    }

    bulkClient.createBatch(request, jobId, contentType, new BulkApiClient.BatchInfoResponseCallback() {
        @Override
        public void onResponse(BatchInfo batchInfo, SalesforceException ex) {
            processResponse(exchange, batchInfo, ex, callback);
        }
    });
}
项目:Camel    文件:ProtobufMarshalAndUnmarshallTest.java   
@Test
public void testMarshalAndUnmarshalWithDSL3() throws Exception {
    try {
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:unmarshalC").unmarshal().protobuf(new CamelException("wrong instance"))
                    .to("mock:reverse");
            }
        });
        fail("Expect the exception here");
    } catch (Exception ex) {
        assertTrue("Expect FailedToCreateRouteException", ex instanceof FailedToCreateRouteException);
        assertTrue("Get a wrong reason", ex.getCause() instanceof IllegalArgumentException);
    }
}
项目:Camel    文件:SplitterTest.java   
protected RouteBuilder createRouteBuilder() {
    return new RouteBuilder() {
        public void configure() {
            onException(CamelException.class).to("mock:failed");

            from("direct:seqential").split(body().tokenize(","), new UseLatestAggregationStrategy()).to("mock:result");
            from("direct:parallel").split(body().tokenize(","), new MyAggregationStrategy()).parallelProcessing().to("mock:result");
            from("direct:parallelAggregate").split(body().tokenize(","), new MyAggregationStrategy()).parallelProcessing().parallelAggregate().to("mock:result");
            from("direct:streaming").split(body().tokenize(",")).streaming().to("mock:result");
            from("direct:parallel-streaming").split(body().tokenize(","), new MyAggregationStrategy()).parallelProcessing().streaming().to("mock:result");
            from("direct:exception")
                    .split(body().tokenize(","))
                    .aggregationStrategy(new MyAggregationStrategy())
                    .parallelProcessing()
                    .process(new Processor() {
                        public void process(Exchange exchange) throws Exception {
                            String string = exchange.getIn().getBody(String.class);
                            if ("Exception".equals(string)) {
                                throw new CamelException("Just want to throw exception here");
                            }

                        }
                    }).to("mock:result");
            from("direct:simple").split(body()).to("mock:result");
        }
    };
}
项目:Camel    文件:RedeliveryErrorHandlerLogHandledTest.java   
public void testRedeliveryErrorHandlerAllOptions() throws Exception {
    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            errorHandler(defaultErrorHandler()
                    .maximumRedeliveries(3)
                    .logExhausted(true).logHandled(true).logRetryStackTrace(true).logStackTrace(true)
                    .retryAttemptedLogLevel(LoggingLevel.WARN).retriesExhaustedLogLevel(LoggingLevel.ERROR));

            from("direct:bar")
                .throwException(new CamelException("Camel rocks"));
        }
    });
    context.start();

    getMockEndpoint("mock:handled").expectedMessageCount(0);

    try {
        template.sendBody("direct:bar", "Hello World");
        fail("Should thrown an exception");
    } catch (CamelExecutionException e) {
        CamelException cause = assertIsInstanceOf(CamelException.class, e.getCause());
        assertEquals("Camel rocks", cause.getMessage());
    }

    assertMockEndpointsSatisfied();
}
项目:Camel    文件:CustomExceptionPolicyStrategyTest.java   
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        // START SNIPPET e1
        public void configure() throws Exception {
            // configure the error handler to use my policy instead of the default from Camel
            errorHandler(deadLetterChannel("mock:error").exceptionPolicyStrategy(new MyPolicy()));

            onException(MyPolicyException.class)
                .maximumRedeliveries(1)
                .setHeader(MESSAGE_INFO, constant("Damm my policy exception"))
                .to(ERROR_QUEUE);

            onException(CamelException.class)
                .maximumRedeliveries(3)
                .setHeader(MESSAGE_INFO, constant("Damm a Camel exception"))
                .to(ERROR_QUEUE);
            // END SNIPPET e1

            from("direct:a").process(new Processor() {
                public void process(Exchange exchange) throws Exception {
                    String s = exchange.getIn().getBody(String.class);
                    if ("Hello Camel".equals(s)) {
                        throw new CamelExchangeException("Forced for testing", exchange);
                    }
                    exchange.getOut().setBody("Hello World");
                }
            }).to("mock:result");
        }
    };
}
项目:Camel    文件:LoopTestProcessor.java   
public void process(Exchange exchange) {
    Integer c = exchange.getProperty(Exchange.LOOP_SIZE, Integer.class);
    Integer i = exchange.getProperty(Exchange.LOOP_INDEX, Integer.class);
    if (c == null || c.intValue() != this.count) {
        exchange.setException(new CamelException(
            "Invalid count value.  Expected " + this.count + " but was " + c));
    }
    if (i == null || i.intValue() != this.index++) {
        exchange.setException(new CamelException(
            "Invalid index value.  Expected " + this.index + " but was " + i));
    }
}
项目:Camel    文件:TryProcessorTest.java   
public void process(Exchange exchange) throws Exception {
    handled = true;

    assertEquals("Should not be marked as failed", false, exchange.isFailed());

    Exception e = (Exception)exchange.getProperty(Exchange.EXCEPTION_CAUGHT);
    assertNotNull("There should be an exception", e);

    // If we handle CamelException it is what we should have as an exception caught
    CamelException cause = assertIsInstanceOf(CamelException.class, e.getCause());
    assertNotNull(cause);
    assertEquals("Force to fail", cause.getMessage());
}
项目:Camel    文件:SplitterParallelBigFileTest.java   
public void xxxtestSplitParallelBigFile() throws Exception {
    StopWatch watch = new StopWatch();

    NotifyBuilder builder = new NotifyBuilder(context).whenDone(lines + 1).create();
    boolean done = builder.matches(120, TimeUnit.SECONDS);

    log.info("Took " + TimeUtils.printDuration(watch.stop()));

    if (!done) {
        throw new CamelException("Could not split file in 2 minutes");
    }

    // need a little sleep for capturing memory profiling
    // Thread.sleep(60 * 1000);
}
项目:Camel    文件:ZooKeeperComponent.java   
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
    if (getCamelContext() == null) {
        throw new CamelException("No Camel context has been provided to this zookeeper component");
    }

    ZooKeeperConfiguration config = getConfiguration().copy();
    extractConfigFromUri(uri, config);
    setProperties(config, parameters);

    return new ZooKeeperEndpoint(uri, this, config);
}
项目:Camel    文件:AvroMarshalAndUnmarshallTest.java   
@Test
public void testMarshalAndUnmarshalWithDSL3() throws Exception {
    try {
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:unmarshalC").unmarshal().avro(new CamelException("wrong schema"))
                        .to("mock:reverse");
            }
        });
        fail("Expect the exception here");
    } catch (Exception ex) {
        // expected
    }
}
项目:Camel    文件:SipSubscriptionListener.java   
private void dispatchExchange(Object response) throws CamelException {
    LOG.debug("Consumer Dispatching the received notification along the route");
    Exchange exchange = sipSubscriber.getEndpoint().createExchange(ExchangePattern.InOnly);
    exchange.getIn().setBody(response);
    try {
        sipSubscriber.getProcessor().process(exchange);
    } catch (Exception e) {
        throw new CamelException("Error in consumer while dispatching exchange", e);
    }
}
项目:Camel    文件:AbstractCamelContextFactoryBean.java   
/**
 * Strategy to install all available routes into the context
 */
protected void installRoutes() throws Exception {
    List<RouteBuilder> builders = new ArrayList<RouteBuilder>();

    // lets add RoutesBuilder's added from references
    if (getBuilderRefs() != null) {
        for (RouteBuilderDefinition builderRef : getBuilderRefs()) {
            RoutesBuilder routes = builderRef.createRoutes(getContext());
            if (routes != null) {
                this.builders.add(routes);
            } else {
                throw new CamelException("Cannot find any routes with this RouteBuilder reference: " + builderRef);
            }
        }
    }

    // install already configured routes
    for (RoutesBuilder routeBuilder : this.builders) {
        getContext().addRoutes(routeBuilder);
    }

    // install builders
    for (RouteBuilder builder : builders) {
        // Inject the annotated resource
        postProcessBeforeInit(builder);
        getContext().addRoutes(builder);
    }
}
项目:Camel    文件:KafkaProducer.java   
@SuppressWarnings("unchecked")
protected ProducerRecord createRecorder(Exchange exchange) throws CamelException {
    String topic = endpoint.getTopic();
    if (!endpoint.isBridgeEndpoint()) {
        topic = exchange.getIn().getHeader(KafkaConstants.TOPIC, topic, String.class);
    }
    if (topic == null) {
        throw new CamelExchangeException("No topic key set", exchange);
    }
    Object partitionKey = exchange.getIn().getHeader(KafkaConstants.PARTITION_KEY);
    boolean hasPartitionKey = partitionKey != null;

    Object messageKey = exchange.getIn().getHeader(KafkaConstants.KEY);
    boolean hasMessageKey = messageKey != null;

    Object msg = exchange.getIn().getBody();

    ProducerRecord record;
    if (hasPartitionKey && hasMessageKey) {
        record = new ProducerRecord(topic, new Integer(partitionKey.toString()), messageKey, msg);
    } else if (hasMessageKey) {
        record = new ProducerRecord(topic, messageKey, msg);
    } else {
        log.warn("No message key or partition key set");
        record = new ProducerRecord(topic, msg);
    }
    return record;
}
项目:Camel    文件:KafkaProducerTest.java   
@Test(expected = CamelException.class)
public void processRequiresTopicInEndpointOrInHeader() throws Exception {
    endpoint.setTopic(null);
    Mockito.when(exchange.getIn()).thenReturn(in);
    in.setHeader(KafkaConstants.PARTITION_KEY, "4");
    producer.process(exchange);
}
项目:Camel    文件:SjmsComponent.java   
/**
 * Helper method used to verify that when there is a namedReplyTo value we
 * are using the InOut MEP. If namedReplyTo is defined and the MEP is InOnly
 * the endpoint won't be expecting a reply so throw an error to alert the
 * user.
 *
 * @param parameters {@link Endpoint} parameters
 * @throws Exception throws a {@link CamelException} when MEP equals InOnly
 *                   and namedReplyTo is defined.
 */
private static void validateMepAndReplyTo(Map<String, Object> parameters) throws Exception {
    boolean namedReplyToSet = parameters.containsKey("namedReplyTo");
    boolean mepSet = parameters.containsKey("exchangePattern");
    if (namedReplyToSet && mepSet) {
        if (!parameters.get("exchangePattern").equals(ExchangePattern.InOut.toString())) {
            String namedReplyTo = (String) parameters.get("namedReplyTo");
            ExchangePattern mep = ExchangePattern.valueOf((String) parameters.get("exchangePattern"));
            throw new CamelException("Setting parameter namedReplyTo=" + namedReplyTo + " requires a MEP of type InOut. Parameter exchangePattern is set to " + mep);
        }
    }
}
项目:Camel    文件:MinaConsumer.java   
@Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
    // close invalid session
    if (session != null) {
        LOG.debug("Closing session as an exception was thrown from MINA");
        session.close();
    }

    // must wrap and rethrow since cause can be of Throwable and we must only throw Exception
    throw new CamelException(cause);
}
项目:Camel    文件:XmlErrorHandlerPolicyTest.java   
@Test
public void sendExceptionToInbound() {
    try {
        inbound.sendBody("exception");
    } catch (Exception exception) {
        assertThat("Exception is incorrect!",
            exception, is(instanceOf(CamelExecutionException.class)));
        assertThat("Exception cause is incorrect!",
            exception.getCause(), is(instanceOf(CamelException.class)));
        assertThat("Exception message is incorrect!",
            exception.getCause().getMessage(), is(equalTo("failure message!")));
        return;
    }
    fail("No exception thrown!");
}
项目:Camel    文件:XmlErrorHandlerLoggingTest.java   
@Test
public void sendExceptionToInbound() {
    try {
        inbound.sendBody("exception");
    } catch (Exception exception) {
        assertThat("Exception is incorrect!",
            exception, is(instanceOf(CamelExecutionException.class)));
        assertThat("Exception cause is incorrect!",
            exception.getCause(), is(instanceOf(CamelException.class)));
        assertThat("Exception message is incorrect!",
            exception.getCause().getMessage(), is(equalTo("failure message!")));
        return;
    }
    fail("No exception thrown!");
}
项目:Camel    文件:MisspelledRouteRefTest.java   
public void testApplicationContextFailed() {
    try {
        Main main = new Main();
        main.setApplicationContextUri("org/apache/camel/spring/issues/MisspelledRouteRefTest.xml");
        main.start();
        fail("Should have thrown an exception");
    } catch (Exception e) {
        //expected but want to see what it looks like...
        LOG.debug("Exception message : " + e.getMessage());

        CamelException cause = (CamelException) e.getCause();
        assertEquals("Cannot find any routes with this RouteBuilder reference: RouteBuilderRef[xxxroute]", cause.getMessage());
    }
}
项目:Camel    文件:JcloudsComputeProducer.java   
/**
 * Create a node with the specified group.
 */
protected void createNode(Exchange exchange) throws CamelException {
    String group = getGroup(exchange);
    String imageId = getImageId(exchange);
    String locationId = getLocationId(exchange);
    String hardwareId = getHardwareId(exchange);

    if (ObjectHelper.isEmpty(group)) {
        throw new CamelExchangeException("Group must be specific in the URI or as exchange property for the destroy node operation.", exchange);
    }
    TemplateBuilder builder = computeService.templateBuilder();
    builder.any();

    if (ObjectHelper.isNotEmpty(locationId)) {
        builder.locationId(locationId);
    }
    if (ObjectHelper.isNotEmpty(imageId)) {
        builder.imageId(imageId);
    }
    if (ObjectHelper.isNotEmpty(hardwareId)) {
        builder.hardwareId(hardwareId);
    }

    try {
        Set<? extends NodeMetadata> nodeMetadatas = computeService.createNodesInGroup(group, 1, builder.build());
        exchange.getOut().setBody(nodeMetadatas);
        exchange.getOut().setHeaders(exchange.getIn().getHeaders());
    } catch (RunNodesException e) {
        throw new CamelExchangeException("Error creating jclouds node.", exchange, e);
    }
}
项目:Camel    文件:JcloudsComputeProducer.java   
/**
 * Runs a script on the target node.
 */
protected void runScriptOnNode(Exchange exchange) throws CamelException {
    String script = exchange.getIn().getBody(String.class);
    String nodeId = getNodeId(exchange);
    String user = getUser(exchange);

    LoginCredentials credentials = null;

    if (ObjectHelper.isNotEmpty(user)) {
        credentials = LoginCredentials.builder().user(user).build();
    }
    ExecResponse execResponse = null;

    if (credentials == null) {
        execResponse = computeService.runScriptOnNode(nodeId, script);
    } else {
        execResponse = computeService.runScriptOnNode(nodeId, script, RunScriptOptions.Builder.overrideLoginCredentials(credentials).runAsRoot(false));
    }

    if (execResponse == null) {
        throw new CamelExchangeException("Failed to receive response for run script operation on node: " + nodeId + " using script: " + script, exchange);
    }

    exchange.setProperty(JcloudsConstants.RUN_SCRIPT_ERROR, execResponse.getError());
    exchange.setProperty(JcloudsConstants.RUN_SCRIPT_EXIT_CODE, execResponse.getExitStatus());
    exchange.getOut().setBody(execResponse.getOutput());
}
项目:Camel    文件:Jt400Endpoint.java   
/**
 * Creates a new AS/400 data queue endpoint using the specified connection
 * pool.
 */
protected Jt400Endpoint(String endpointUri, Jt400Component component, AS400ConnectionPool connectionPool) throws CamelException {
    super(endpointUri, component);
    ObjectHelper.notNull(connectionPool, "connectionPool");
    try {
        configuration = new Jt400Configuration(endpointUri, connectionPool);
    } catch (URISyntaxException e) {
        throw new CamelException("Unable to parse URI for " + URISupport.sanitizeUri(endpointUri), e);
    }
}
项目:Camel    文件:IgniteCacheEndpoint.java   
private IgniteCache<Object, Object> obtainCache() throws CamelException {
    IgniteCache<Object, Object> cache = ignite().cache(cacheName);
    if (cache == null) {
        if (failIfInexistentCache) {
            throw new CamelException(String.format("Ignite cache %s doesn't exist, and failIfInexistentCache is true", cacheName));
        }
        cache = ignite().createCache(cacheName);
    }

    return cache;
}
项目:Camel    文件:IgniteCacheTest.java   
@Test
public void testAddEntryNoCacheCreation() {
    try {
        template.requestBodyAndHeader("ignite:cache:testcache2?operation=PUT&failIfInexistentCache=true", "1234", IgniteConstants.IGNITE_CACHE_KEY, "abcd");
    } catch (Exception e) {
        assert_().that(ObjectHelper.getException(CamelException.class, e).getMessage()).startsWith("Ignite cache testcache2 doesn't exist");
        return;
    }

    fail("Should have thrown an exception");
}
项目:Camel    文件:Mina2Consumer.java   
@Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
    if (cause instanceof IOException) {
        LOG.debug("IOExceptions are automatically handled by MINA");
        return;
    }
    // close invalid session
    if (session != null) {
        LOG.warn("Closing session as an exception was thrown from MINA");
        session.close(true);
    }

    // must wrap and rethrow since cause can be of Throwable and we must only throw Exception
    throw new CamelException(cause);
}
项目:Camel    文件:DnsLookupProducer.java   
@Override
public void process(Exchange exchange) throws Exception {
    String dnsName = exchange.getIn().getHeader(DnsConstants.DNS_NAME, String.class);
    ObjectHelper.notEmpty(dnsName, "Header " + DnsConstants.DNS_NAME);

    Object type = exchange.getIn().getHeader(DnsConstants.DNS_TYPE);
    Integer dnsType = null;
    if (type != null) {
        dnsType = Type.value(String.valueOf(type));
    }
    Object dclass = exchange.getIn().getHeader(DnsConstants.DNS_CLASS);
    Integer dnsClass = null;
    if (dclass != null) {
        dnsClass = DClass.value(String.valueOf(dclass));
    }

    Lookup lookup = (dnsClass == null)
            ? (dnsType == null ? new Lookup(dnsName) : new Lookup(dnsName, dnsType))
            : new Lookup(dnsName, dnsType, dnsClass);

    lookup.run();
    if (lookup.getAnswers() != null) {
        exchange.getIn().setBody(lookup.getAnswers());
    } else {
        throw new CamelException(lookup.getErrorString());
    }
}
项目:Camel    文件:ClientModeTCPNettyServerBootstrapFactory.java   
protected Channel openChannel(ChannelFuture channelFuture) throws Exception {
    // blocking for channel to be done
    if (LOG.isTraceEnabled()) {
        LOG.trace("Waiting for operation to complete {} for {} millis", channelFuture, configuration.getConnectTimeout());
    }
    // here we need to wait it in other thread
    final CountDownLatch channelLatch = new CountDownLatch(1);
    channelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            channelLatch.countDown();
        }
    });

    try {
        channelLatch.await(configuration.getConnectTimeout(), TimeUnit.MILLISECONDS);
    } catch (InterruptedException ex) {
        throw new CamelException("Interrupted while waiting for " + "connection to "
                + configuration.getAddress());
    }

    if (!channelFuture.isDone() || !channelFuture.isSuccess()) {
        ConnectException cause = new ConnectException("Cannot connect to " + configuration.getAddress());
        if (channelFuture.getCause() != null) {
            cause.initCause(channelFuture.getCause());
        }
        throw cause;
    }
    Channel answer = channelFuture.getChannel();

    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating connector to address: {}", configuration.getAddress());
    }
    return answer;
}
项目:Camel    文件:NettyProducer.java   
protected Channel openChannel(ChannelFuture channelFuture) throws Exception {
    // blocking for channel to be done
    if (LOG.isTraceEnabled()) {
        LOG.trace("Waiting for operation to complete {} for {} millis", channelFuture, configuration.getConnectTimeout());
    }
    // here we need to wait it in other thread
    final CountDownLatch channelLatch = new CountDownLatch(1);
    channelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            channelLatch.countDown();
        }
    });

    try {
        channelLatch.await(configuration.getConnectTimeout(), TimeUnit.MILLISECONDS);
    } catch (InterruptedException ex) {
        throw new CamelException("Interrupted while waiting for " + "connection to "
                                 + configuration.getAddress());
    }


    if (!channelFuture.isDone() || !channelFuture.isSuccess()) {
        ConnectException cause = new ConnectException("Cannot connect to " + configuration.getAddress());
        if (channelFuture.getCause() != null) {
            cause.initCause(channelFuture.getCause());
        }
        throw cause;
    }
    Channel answer = channelFuture.getChannel();
    // to keep track of all channels in use
    allChannels.add(answer);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating connector to address: {}", configuration.getAddress());
    }
    return answer;
}
项目:Camel    文件:TidyMarkupDataFormat.java   
/**
 * Return the HTML Markup as an {@link org.w3c.dom.Node}
 * 
 * @param inputStream
 *            The input Stream to convert
 * @return org.w3c.dom.Node The HTML Markup as a DOM Node
 * @throws CamelException
 */
public Node asNodeTidyMarkup(InputStream inputStream) throws CamelException {
    XMLReader parser = createTagSoupParser();
    StringWriter w = new StringWriter();
    parser.setContentHandler(createContentHandler(w));

    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        DOMResult result = new DOMResult();
        transformer.transform(new SAXSource(parser, new InputSource(inputStream)), result);
        return result.getNode();
    } catch (Exception e) {
        throw new CamelException("Failed to convert the HTML to tidy Markup", e);
    }
}
项目:Camel    文件:ProtobufDataFormat.java   
protected Message loadDefaultInstance(final String className, final CamelContext context) throws CamelException, ClassNotFoundException {
    Class<?> instanceClass = context.getClassResolver().resolveMandatoryClass(className);
    if (Message.class.isAssignableFrom(instanceClass)) {
        try {
            Method method = instanceClass.getMethod("getDefaultInstance");
            return (Message) method.invoke(null);
        } catch (final Exception ex) {
            throw new CamelException("Can't set the defaultInstance of ProtobufferDataFormat with "
                    + className + ", caused by " + ex);
        }
    } else {
        throw new CamelException("Can't set the defaultInstance of ProtobufferDataFormat with "
                + className + ", as the class is not a subClass of com.google.protobuf.Message");
    }
}
项目:cleverbus    文件:ErrorHandlingTest.java   
@Test
public void testAsyncNestedFatalException() throws Exception {
    class TestRoute extends AbstractBasicRoute {
        @Override
        protected void doConfigure() throws Exception {
            from("direct:start")
                .throwException(new CamelException(new NoDataFoundException("no data")));
        }
    }

    getCamelContext().addRoutes(new TestRoute());

    processAndVerify(true, false, true);
}
项目:camel-cdi    文件:XmlErrorHandlerPolicyTest.java   
@Test
public void sendExceptionToInbound() {
    try {
        inbound.sendBody("exception");
    } catch (Exception exception) {
        assertThat("Exception is incorrect!",
            exception, is(instanceOf(CamelExecutionException.class)));
        assertThat("Exception cause is incorrect!",
            exception.getCause(), is(instanceOf(CamelException.class)));
        assertThat("Exception message is incorrect!",
            exception.getCause().getMessage(), is(equalTo("failure message!")));
        return;
    }
    fail("No exception thrown!");
}
项目:camel-cdi    文件:XmlErrorHandlerLoggingTest.java   
@Test
public void sendExceptionToInbound() {
    try {
        inbound.sendBody("exception");
    } catch (Exception exception) {
        assertThat("Exception is incorrect!",
            exception, is(instanceOf(CamelExecutionException.class)));
        assertThat("Exception cause is incorrect!",
            exception.getCause(), is(instanceOf(CamelException.class)));
        assertThat("Exception message is incorrect!",
            exception.getCause().getMessage(), is(equalTo("failure message!")));
        return;
    }
    fail("No exception thrown!");
}
项目:mdpnp    文件:RtiParticipantInstance.java   
public String getRegisteredType(String className, ClassResolver resolver) throws Exception {
    synchronized (registeredTypes) {
        for (final Map.Entry<String, TypeSupportImpl> entry : registeredTypes.entrySet()) {
            if (entry.getValue().getClass().getName().equals(className)) {
                return entry.getKey();
            }
        }
        // if not found register it
        Class<?> type = resolver.resolveClass(className);
        if (type == null) {
            throw new CamelException("Cannot resolve class " + className);
        }
        Method getInstanceMethod = null;
        Method getTypeNameMethod = null;
        Method registerTypeMethod = null;
        try {
            getInstanceMethod = type.getMethod("get_instance");
            getTypeNameMethod = type.getMethod("get_type_name");
            registerTypeMethod = type.getMethod("register_type", DomainParticipant.class, String.class);
        } catch (Exception e) {
            throw new CamelException("Invalid TypeSupport class " + className);
        }
        TypeSupportImpl inst = (TypeSupportImpl)getInstanceMethod.invoke(null);
        String typeName = (String)getTypeNameMethod.invoke(null);
        if (typeName != null && inst != null) {
            registerTypeMethod.invoke(null, getValue(), typeName);
            registeredTypes.put(typeName, inst);
        }
        return typeName;
    }
}