Camel Proxy and Replacing Exchange body - apache-camel

I have created a proxy for service.
There is a processor in between proxy (request is of type TypeA) and real service (request is of type TypeB).
The Exchange body which comes into the process(Exchange exchange) method is of TypeA.
I am able to access the data using following line of code
TypeA typeA = exchange.getIn().getBody(TypeA.class);
Now, I wanted to change this information to TypeB.
I am adding the body using following line.
exchange.getIn().setBody(typeA);
I got the java.lang.IllegalArgumentException: argument type mismatch
Now, I wanted to call the real service using the Exchange which come out of the Processor.
I tried and got in Processor the following exception
java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.cxf.databinding.AbstractWrapperHelper.createWrapperObject(AbstractWrapperHelpe
The real web service is not getting invoked.
How to fix this.
I am using POJO mode in proxy.

This works without any problems:
private static class ResetBodyRouteBuilder extends RouteBuilder {
#Override
public void configure() {
from("direct:start")
.process(new Processor() {
#Override
public void process(final Exchange exchange) throws Exception {
final ClassA a = exchange.getIn().getBody(ClassA.class);
LOG.info("body = " + a);
exchange.getIn().setBody(new ClassB()); // reset the body
}
})
.log("body = ${body}");
}
}
public class ClassA {
#Override
public String toString() {
return "I'm A";
}
};
public class ClassB {
#Override
public String toString() {
return "I'm B";
}
};
This prints:
[ main] ResetBody INFO body = I'm A
[ main] route1 INFO body = I'm B

Related

Apache Camel: pollEnrich does not call dynamic URI

I have a route to poll the email from the server. In the FunctionRoute I am trying to pass the subject of the email I want to fetch by the IMAP protocol using pollEnrich method in the EmailPollingRoute. Currently I am facing problem to make a dynamic URI endpoint. I noticed the headers are being cleared before calling the pollEnrich method. Therefore I tried to use the ${exchangeProperty.subject} but there is no email is fetched. When I set the subject directly in the endpoint as String then the email is being fetched.
How can I set the subject dynamically in the pollEnrich method? The subject is being passed from the FunctionRoute to EmailPollingRoute route.
I appreciate any help
#Component
public class FunctionRoute extends EmailPollingRoute {
static final Logger LOGGER = LoggerFactory.getLogger(FunctionRoute.class);
#Override
public void configure() throws Exception {
from("direct:process_polling_email_function")
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
subject = "ABCD - Test1";
exchange.setProperty("ABCD - Test1");
LOGGER.info("1. subject - " + subject);
}})
//.setProperty("subject", constant("ABCD - Test1"))
//.setHeader("subject", simple("ABCD - Test1"))
.to("direct:process_polling_email");
}
}
#Component
public class EmailPollingRoute extends BaseRouteBuilder {
static final Logger LOGGER = LoggerFactory.getLogger(EmailPollingRoute.class);
public String subject;
#Override
public void configure() throws Exception {
//super.configure();
//2362
//#formatter:off
from("direct:process_polling_email")
.routeId("routeId_EmailPollingRoute")
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
subject = exchange.getProperty("subject", String.class);
LOGGER.info("0001 - subjectB: (" + subject + ")");
}})
.pollEnrich("imaps://XXXXXXX.info"
+ "?username=XXXXX&"
+ "password=XXXXXXX&"
+"folderName=Inbox/Test&"
+"searchTerm.fromSentDate=now-72h&"
+"searchTerm.subject=${exchangeProperty.subject}&"
+"fetchSize=1");
.to("log:newmail");
//#formatter:on
}
}
You can set pollEnrich URI dynamically using simple method, you can also specify timeout in similar way.
.pollEnrich()
.simple("imaps://XXXXXXX.info"
+ "?username=XXXXX&"
+ "password=XXXXXXX&"
+"folderName=Inbox/Test&"
+"searchTerm.fromSentDate=now-72h&"
+"searchTerm.subject=${exchangeProperty.subject}&"
+"fetchSize=1")
.timeout(1000);

Send data to an external resource: why content is null?

I have a simple Camel route. I want to extract a file from the queue and pass it by using POST request to an external resource. This route works and the request reaches an external resource:
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
public class MyRouteBuilder extends RouteBuilder {
#Override
public void configure() throws Exception {
from("activemq:alfresco-queue")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
byte[] bytes = exchange.getIn().getBody(byte[].class);
// All of that not working...
// exchange.getIn().setHeader("content", bytes); gives "java.lang.IllegalAgrumentException: Request header is too large"
// exchange.getIn().setBody(bytes, byte[].class); gives "size of content is -1"
// exchange.getIn().setBody(bytes); gives "size of content is -1"
// ???
// ??? But I can print file content here
for(int i=0; i < bytes.length; i++) {
System.out.print((char) bytes[i]);
}
}
})
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.setHeader(Exchange.CONTENT_TYPE, constant("multipart/form-data"))
.to("http://vm-alfce52-31......com:8080/alfresco/s/someco/queuefileuploader?guest=true")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
System.out.println("The response code is: " + exchange.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE));
}
});
}
}
The question is that the payload of the request is lost:
// somewhere on an external resource
Content content = request.getContent();
long len = content.getSize() // is always == -1.
// the file name is passed successfully
String fileName = request.getHeader("fileName");
How to set and pass the payload of POST request in this route/ processor?
I noticed that ANY data setted by this way is losted too. Only the headers are sent to the remote resource.
By using simple HTML form with <input type="file"> encoded in multipart/form-data I can successfully send all the data to the external resource.
What could be the reason?
Updated.
The following code also gives null-content:
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// this also gives null-content
//multipartEntityBuilder.addBinaryBody("file", exchange.getIn().getBody(byte[].class));
multipartEntityBuilder.addPart("file", new ByteArrayBody(exchange.getIn().getBody(byte[].class), exchange.getIn().getHeader("fileName", String.class)));
exchange.getOut().setBody(multipartEntityBuilder.build().getContent());
/********** This also gives null-content *********/
StringBody username = new StringBody("username", ContentType.MULTIPART_FORM_DATA);
StringBody password = new StringBody("password", ContentType.MULTIPART_FORM_DATA);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntityBuilder.addPart("username", username);
multipartEntityBuilder.addPart("password", password);
String filename = (String) exchange.getIn().getHeader("fileName");
File file = new File(filename);
try(RandomAccessFile accessFile = new RandomAccessFile(file, "rw")) {
accessFile.write(bytes);
}
multipartEntityBuilder.addPart("upload", new FileBody(file, ContentType.MULTIPART_FORM_DATA, filename));
exchange.getIn().setBody(multipartEntityBuilder.build().getContent());
One more detail. If I change this:
exchange.getOut().setBody(multipartEntityBuilder.build().getContent());
To this:
exchange.getOut().setBody(multipartEntityBuilder.build());
I get the following exception on FUSE side (I see it through hawtio management console):
Execution of JMS message listener failed.
Caused by: [org.apache.camel.RuntimeCamelException - org.apache.camel.InvalidPayloadException:
No body available of type: java.io.InputStream but has value: org.apache.http.entity.mime.MultipartFormEntity#26ee73 of type:
org.apache.http.entity.mime.MultipartFormEntity on: JmsMessage#0x1cb83b9.
Caused by: No type converter available to convert from type: org.apache.http.entity.mime.MultipartFormEntity to the required type:
java.io.InputStream with value org.apache.http.entity.mime.MultipartFormEntity#26ee73. Exchange[ID-63-DP-TAV-55652-1531889677177-5-1]. Caused by:
[org.apache.camel.NoTypeConversionAvailableException - No type converter available to convert from type:
org.apache.http.entity.mime.MultipartFormEntity to the required type: java.io.InputStream with value org.apache.http.entity.mime.MultipartFormEntity#26ee73]]
I write a small servlet application and get the content in the doPost(...) method from the HttpServletRequest object.
The problem was with the WebScriptRequest object on the external system (Alfresco) side.
#Bedla, thanks for your advices!
On the Alfresco side the problem can be solved as follows:
public class QueueFileUploader extends DeclarativeWebScript {
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status) {
HttpServletRequest httpServletRequest = WebScriptServletRuntime.getHttpServletRequest(req);
// calling methods of httpServletRequest object and retrieving the content
...
The route:
public class MyRouteBuilder extends RouteBuilder {
#Override
public void configure() throws Exception {
from("activemq:alfresco-queue")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntityBuilder.addPart("file", new ByteArrayBody(exchange.getIn().getBody(byte[].class),
exchange.getIn().getHeader("fileName", String.class)));
exchange.getIn().setBody(multipartEntityBuilder.build().getContent());
}
})
.setHeader(Exchange.HTTP_METHOD, constant(org.apache.camel.component.http4.HttpMethods.POST))
.to("http4://localhost:8080/alfresco/s/someco/queuefileuploader?guest=true")
// .to("http4://localhost:8080/ServletApp/hello")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
System.out.println("The response code is: " +
exchange.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE));
}
});
}
}

Camel bean component invokes cached instance of #Named / #Dependent bean

In our application we are using Apache Camel with camel-cdi component in JBoss EAP 7.1 environment. After upgrade of Apache Camel to actual version the application started to behave incorrectly in parallel execution.
I have found, that bean component invokes always the same instance. From my understanding, bean with #Dependent scope should be always fresh instance for every CDI lookup.
I have tried endpoint parameter cache=false, which should be default, but the behavior stays the same. Also tried to specify #Dependent, which should be default too.
Attaching MCVE, which fails on Apache Camel 2.20.0 and newer. Works well with 2.19.5 and older. Full reproducible project on Github.
#ApplicationScoped
#Startup
#ContextName("cdi-context")
public class MainRouteBuilder extends RouteBuilder {
public void configure() throws Exception {
from("timer:test")
.to("bean:someDependentBean?cache=false");
}
}
#Named
//#Dependent //Dependent is default
public class SomeDependentBean implements Processor {
private int numOfInvocations = 0;
private static Logger log = LoggerFactory.getLogger(SomeDependentBean.class);
public void process(Exchange exchange) throws Exception {
log.info("This is: "+toString());
numOfInvocations++;
if (numOfInvocations!=1){
throw new IllegalStateException(numOfInvocations+"!=1");
} else {
log.info("OK");
}
}
}
Is there anything I can do in our application to change this behavior and use actual version of Apache Camel?
EDIT:
Removing tags camel-cdi and jboss-weld. I have created unit test, to simulate this situation without dependencies to camel-cdi and Weld. This test contains assertion to test JndiRegistry#lookup, which returns correct instance. According this test I believe, the issue is in bean component itself. Fails with version >=2.20.0 and passes with <=2.19.5
public class CamelDependentTest extends CamelTestSupport {
private Context context;
private JndiRegistry registry;
#Override
protected RoutesBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
#Override
public void configure() throws Exception {
from("direct:in")
.to("bean:something?cache=false");
}
};
}
#Override
protected JndiRegistry createRegistry() throws Exception {
JndiRegistry registry = super.createRegistry();
registry.bind("something", new SomeDependentBean());
this.context = registry.getContext();
this.registry = registry;
return registry;
}
#Test
public void testFreshBeanInContext() throws Exception{
SomeDependentBean originalInstance = registry.lookup("something", SomeDependentBean.class);
template.sendBody("direct:in",null);
context.unbind("something");
context.bind("something", new SomeDependentBean()); //Bind new instance to Context
Assert.assertNotSame(registry.lookup("something"), originalInstance); //Passes, the issue is not in JndiRegistry.
template.sendBody("direct:in",null); //fails, uses cached instance of SameDependentBean
}
}
According CAMEL-12610 is Processor supposed to be singleton scope. This behavior was introduced in version 2.20.0. Do not implement Processor interface, instead annotate invokable method as #Handler.
Replace
#Named
public class SomeDependentBean implements Processor {
public void process(Exchange exchange) throws Exception {
}
}
with
#Named
public class SomeDependentBean {
#Handler
public void process(Exchange exchange) throws Exception {
}
}
If you cannot afford that as me, because it is breaking behavior for our app extensions, I have implemented simple component. This component have no caching and allows to invoke Processor directly from registry.
CdiEndpoint class
public class CdiEndpoint extends ProcessorEndpoint {
private String beanName;
protected CdiEndpoint(String endpointUri, Component component) {
super(endpointUri, component);
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
#Override
protected void onExchange(Exchange exchange) throws Exception {
Object target = getCamelContext().getRegistry().lookupByName(beanName);
Processor processor = getCamelContext().getTypeConverter().tryConvertTo(Processor.class, target);
if (processor != null){
processor.process(exchange);
} else {
throw new RuntimeException("CDI bean "+beanName+" not found");
}
}
}
CdiComponent class
public class CdiComponent extends DefaultComponent {
#Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
CdiEndpoint endpoint = new CdiEndpoint(uri, this);
endpoint.setBeanName(remaining);
return endpoint;
}
}
Usage
public void configure() throws Exception {
getContext().addComponent("cdi", new CdiComponent());
from("direct:in")
.to("cdi:something");
}

Mock not found in the registry for Camel route test

I am trying to test a Camel route (polling messages from an SQS queue) containing
.bean("messageParserProcessor")
where messageParserProcessor is a Processor.
The test:
public class SomeTest extends CamelTestSupport {
private final String queueName = ...;
private final String producerTemplateUri = "aws-sqs://" + queueName + ...;
private static final String MESSAGE_PARSER_PROCESSOR_MOCK_ENDPOINT = "mock:messageParserProcessor";
#EndpointInject(uri = MESSAGE_PARSER_PROCESSOR_MOCK_ENDPOINT)
protected MockEndpoint messageParserProcessor;
#Override
public boolean isUseAdviceWith() {
return true;
}
#Before
public void setUpContext() throws Exception {
context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() {
#Override
public void configure() throws Exception {
interceptSendToEndpoint("bean:messageParserProcessor")
.skipSendToOriginalEndpoint()
.process(MESSAGE_PARSER_PROCESSOR_MOCK_ENDPOINT);
}
});
}
#Test
public void testParser() throws Exception {
context.start();
String expectedBody = "test";
messageParserProcessor.expectedBodiesReceived(expectedBody);
ProducerTemplate template = context.createProducerTemplate();
template.sendBody(producerTemplateUri, expectedBody);
messageParserProcessor.assertIsSatisfied();
context.stop();
}
}
When I run the test I get this error:
org.apache.camel.FailedToCreateRouteException:
Failed to create route route1 at:
>>> InterceptSendToEndpoint[bean:messageParserProcessor -> [process[ref:mock:messageParserProcessor]]] <<< in route: Route(route1)[[From[aws-sqs://xxx...
because of No bean could be found in the registry for: mock:messageParserProcessor of type: org.apache.camel.Processor
Same error if I replace interceptSendToEndpoint(...) with mockEndpointsAndSkip("bean:messageParserProcessor")
The test can be executed (but obviously doesn't pass) when I don't use a mock:
interceptSendToEndpoint("bean:messageParserProcessor")
.skipSendToOriginalEndpoint()
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {}
});
So the problem is the mock that is not found, what is wrong in the way I create it?
So I found a workaround to retrieve mocks from the registry:
interceptSendToEndpoint("bean:messageParserProcessor")
.skipSendToOriginalEndpoint()
.bean(getMockEndpoint(MESSAGE_PARSER_PROCESSOR_MOCK_ENDPOINT));
// Instead of
// .process(MESSAGE_PARSER_PROCESSOR_MOCK_ENDPOINT);
But I still don't understand why using .process("mock:someBean") doesn't work...

camel return value from external Web Service

I need to invoke an external Web service running on WildFly from camel.
I managed to invoke it using the following route:
public class CamelRoute extends RouteBuilder {
final String cxfUri =
"cxf:http://localhost:8080/DemoWS/HelloWorld?" +
"serviceClass=" + HelloWorld.class.getName();
#Override
public void configure() throws Exception {
from("direct:start")
.id("wsClient")
.log("${body}")
.to(cxfUri + "&defaultOperationName=greet");
}
}
My question is how to get the return value from the Web service invocation ? The method used returns a String :
#WebService
public class HelloWorld implements Hello{
#Override
public String greet(String s) {
// TODO Auto-generated method stub
return "Hello "+s;
}
}
If the service in the Wild Fly returns the value then to see the values you can do the below
public class CamelRoute extends RouteBuilder {
final String cxfUri =
"cxf:http://localhost:8080/DemoWS/HelloWorld?" +
"serviceClass=" + HelloWorld.class.getName();
#Override
public void configure() throws Exception {
from("direct:start")
.id("wsClient")
.log("${body}")
.to(cxfUri + "&defaultOperationName=greet").log("${body}");
//beyond this to endpoint you can as many number of componenets to manipulate the response data.
}
}
The second log will log the response from the web service that you are returning. If you need to manipulate or do some routing and transformation with the response then you should look at the type of the response and accordingly you should use appropriate transformer.
Hope this helps.

Resources