2018-03-13 23:45:55 +09:00
|
|
|
/*
|
2019-01-02 18:55:26 +08:00
|
|
|
* Copyright (C) 2018-2019 Lightbend Inc. <https://www.lightbend.com>
|
2018-03-13 23:45:55 +09:00
|
|
|
*/
|
|
|
|
|
|
2017-03-16 09:30:00 +01:00
|
|
|
package jdocs.camel;
|
2019-01-12 04:00:53 +08:00
|
|
|
// #ErrorThrowingConsumer
|
2012-07-15 14:12:03 +02:00
|
|
|
import akka.actor.Status;
|
|
|
|
|
import akka.camel.CamelMessage;
|
|
|
|
|
import akka.camel.javaapi.UntypedConsumerActor;
|
2012-09-03 12:08:46 +02:00
|
|
|
import akka.dispatch.Mapper;
|
2012-07-15 14:12:03 +02:00
|
|
|
import org.apache.camel.builder.Builder;
|
|
|
|
|
import org.apache.camel.model.ProcessorDefinition;
|
|
|
|
|
import org.apache.camel.model.RouteDefinition;
|
|
|
|
|
import scala.Option;
|
|
|
|
|
|
2019-01-12 04:00:53 +08:00
|
|
|
public class ErrorThrowingConsumer extends UntypedConsumerActor {
|
2012-07-15 14:12:03 +02:00
|
|
|
private String uri;
|
|
|
|
|
|
2012-10-01 20:35:19 +02:00
|
|
|
private static Mapper<RouteDefinition, ProcessorDefinition<?>> mapper =
|
2019-01-12 04:00:53 +08:00
|
|
|
new Mapper<RouteDefinition, ProcessorDefinition<?>>() {
|
|
|
|
|
public ProcessorDefinition<?> apply(RouteDefinition rd) {
|
|
|
|
|
// Catch any exception and handle it by returning the exception message
|
|
|
|
|
// as response
|
|
|
|
|
return rd.onException(Exception.class)
|
|
|
|
|
.handled(true)
|
|
|
|
|
.transform(Builder.exceptionMessage())
|
|
|
|
|
.end();
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
public ErrorThrowingConsumer(String uri) {
|
2012-07-15 14:12:03 +02:00
|
|
|
this.uri = uri;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public String getEndpointUri() {
|
|
|
|
|
return uri;
|
|
|
|
|
}
|
|
|
|
|
|
2019-01-12 04:00:53 +08:00
|
|
|
public void onReceive(Object message) throws Exception {
|
2012-07-15 14:12:03 +02:00
|
|
|
if (message instanceof CamelMessage) {
|
|
|
|
|
CamelMessage camelMessage = (CamelMessage) message;
|
|
|
|
|
String body = camelMessage.getBodyAs(String.class, getCamelContext());
|
2019-01-12 04:00:53 +08:00
|
|
|
throw new Exception(String.format("error: %s", body));
|
|
|
|
|
} else unhandled(message);
|
2012-07-15 14:12:03 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@Override
|
2019-01-12 04:00:53 +08:00
|
|
|
public Mapper<RouteDefinition, ProcessorDefinition<?>> getRouteDefinitionHandler() {
|
2012-09-03 12:08:46 +02:00
|
|
|
return mapper;
|
2012-07-15 14:12:03 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@Override
|
|
|
|
|
public void preRestart(Throwable reason, Option<Object> message) {
|
2017-03-16 09:30:00 +01:00
|
|
|
getSender().tell(new Status.Failure(reason), getSelf());
|
2012-07-15 14:12:03 +02:00
|
|
|
}
|
|
|
|
|
}
|
2019-01-12 04:00:53 +08:00
|
|
|
// #ErrorThrowingConsumer
|