Apache Camel test expectedBodiesReceived check if the body is null? - java

I have a route that a processor consumes the message and set the body to null.
public class KafkaRedirect implements Processor {
#Override
public void process(final Exchange exchange) throws Exception {
... some logic to send to another party
/**
* This is added to consume the message
*/
exchange.getIn().setBody(null);
}
}
In the test I send message to the route and I want to test if the message is sent and the body is null.
#Test
public void testMyRoute() throws Exception {
final MockEndpoint thirdPartyEndpoin = getMandatoryEndpoint("mock://myRoute", MockEndpoint.class);
context().getRouteDefinition("myRouteId")
.adviceWith(context(), new AdviceWithRouteBuilder() {
#Override
public void configure() throws Exception {
weaveById("myProcessId").after().to(thirdPartyEndpoin);
}
});
startCamelContext();
thirdPartyEndpoin.expectedMessageCount(1);
/* I NEED TO TEST IF THE BODY IS NULL*/
thirdPartyEndpoin.expectedBodiesReceived(null);
template.sendBody(ROUTE_DIRECT_START, "{\"foo\":\"foo\"}");
thirdPartyEndpoin.assertIsSatisfied(TimeUnit.SECONDS.toMillis(EXPECTED_TIMEOUT_SECONDS));
}

Try with something like (typed from top of my head)
thirdPartyEndpoin.message(0).body().isNull();

Related

Transfer Date header removed from Camel DefaultHeaderFilterStrategy

I was try to hit REST API with authorization from two header fileds: Authorization and Date but Date field has removed from DefaultHeaderFilterStrategy. I was try to replace it with mine filter and set it into Jetty client, but Date header still missing into RequestProcessor and RestProcessor. I need to can transfer this header globally for all our requests. Here is a parts of my code.
#Component
public class RestAPIClientRoute extends RouteBuilder {
#Autowired
private CamelContext camelContext;
#Override
public void configure() throws Exception {
JettyHttpComponent jettyComponent = camelContext.getComponent("jetty", JettyHttpComponent.class);
jettyComponent.setHeaderFilterStrategy(new HeaderFilter());
restConfiguration().component("jetty").scheme("http").port(80).host("localhost");
interceptSendToEndpoint("rest:post:*").process(new Processor() {
public void process(Exchange exchange) {
Properties authProperties = CryptoUtil.duoAuthRequestEncode( duoConfig,"POST", exchange);
Message msg = exchange.getMessage();
msg.setHeader("Authorization", "Basic " + authProperties.getProperty("auth"));
msg.setHeader("Date", authProperties.getProperty("timestamp"));
}
});
rest("/rest")
.post("/accounts/v1/account/list")
.to("direct:hello");
from("direct:hello")
.process(new RequestProcessor());
from("timer:rest-client?period=60s")
.to("direct:accountList");
from("direct:accountList")
.to("rest:post:/rest/accounts/v1/account/list")
.process(new RestProcessor());
}
}
#Component
public class HeaderFilter implements HeaderFilterStrategy {
#Override
public boolean applyFilterToCamelHeaders(String headerName, Object headerValue, Exchange exchange) {
return false;
}
#Override
public boolean applyFilterToExternalHeaders(String headerName, Object headerValue, Exchange exchange) {
return false;
}
}
Actually the problem is coming from the REST component. He set HeaderFilter which override the other setted filter in HTTP component. REST component can not set HeaderFilterStrategy and always use default one. I was start to use only http component with setted mine customised filter instead rest and now can transfer deleted headers from DefaultHeaderFilterStrategy.
I replace it
.to("rest:post:/rest/accounts/v1/account/list")
with
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.setHeader(Exchange.HTTP_QUERY, constant(urlQuery))
.to("https://host.domain.com/rest/accounts/v1/account/list")

Getting invalid characters in camel route exchange body()

I am trying to read email content from a email "*.msg" file. But getting some invalid character, I have no idea what is this, please help me read email body content.
Camel Route
#Override
public void configure() throws Exception {
from(SOURCE_PATH).process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
final EmailResponseModel erm = new EmailResponseModel();
erm.setEmail(exchange.getIn().getBody(String.class));
exchange.getIn().setBody(erm, DBObject.class);
}
}).to(DESTINATION_PATH);
}
Invalid String in response of this line of code exchange.getIn().getBody(String.class)
��\u0011ࡱ\u001a�\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000

Using a http proxy with Apache Camel's http4 endpoint

I'm attempting to use a http proxy with Camel's http4 component. The proxy works when testing using Intellij's HTTP Proxy "Check Connection" option.
However I don't know how to configure it correctly via Camel. When running the following integration test a "ConnectException: Connection timed out" is thrown. Can anyone clarify how to set the proxy details correctly please?
public class SimpleHttpProxyIT extends CamelTestSupport {
public static final String DIRECT_START = "direct:start";
public static final String MOCK_RESULT = "mock:result";
#Produce(uri = DIRECT_START)
protected ProducerTemplate basic;
#EndpointInject(uri = MOCK_RESULT)
protected MockEndpoint resultEndpoint;
#Test
public void testBasic() throws Exception {
basic.sendBody(null);
resultEndpoint.setExpectedMessageCount(1);
resultEndpoint.assertIsSatisfied();
}
#Override
public RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
#Override
public void configure() throws Exception {
from(DIRECT_START)
.id("SunriseTest")
.log(LoggingLevel.INFO, "About to hit sunrise")
.setHeader(Exchange.HTTP_URI, simple("http://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400"))
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
exchange.getProperties().put("http.proxyAuthHost", "myproxy.company.org");
exchange.getProperties().put("http.proxyAuthPort", "10000");
exchange.getProperties().put("http.proxyAuthMethod", "Basic");
exchange.getProperties().put("http.proxyAuthUsername", "myusername");
exchange.getProperties().put("http.proxyAuthPassword", "mypassword");
}
})
.recipientList(simple("http4:dummyhost"))
.log(LoggingLevel.INFO, "Done")
.to(MOCK_RESULT);
}
};
}
}
I would think it should should be exchange.setProperty(...)
Setting the properties in the URI worked. I misread the documentation on "Using Proxy Settings Outside of the URI" (http://camel.apache.org/http4.html) as this was referring to setting them on the context, not the exchange.
public class SimpleHttpProxyIT extends CamelTestSupport {
public static final String DIRECT_START = "direct:start";
public static final String MOCK_RESULT = "mock:result";
#Produce(uri = DIRECT_START)
protected ProducerTemplate basic;
#EndpointInject(uri = MOCK_RESULT)
protected MockEndpoint resultEndpoint;
#Test
public void testBasic() throws Exception {
basic.sendBody(null);
resultEndpoint.setExpectedMessageCount(1);
resultEndpoint.assertIsSatisfied();
}
#Override
public RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
#Override
public void configure() throws Exception {
from(DIRECT_START)
.id("SunriseTest")
.log(LoggingLevel.INFO, "About to hit sunrise")
.setHeader(Exchange.HTTP_URI, simple("http://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400"))
.recipientList(simple("http4:dummyhost?proxyAuthHost=myproxy.company.org&proxyAuthPort=10000&proxyAuthUsername=myusername&proxyAuthPassword=mypassword"))
.log(LoggingLevel.INFO, "Done")
.to(MOCK_RESULT);
}
};
}
}

Camel Routes started but not run when using Camel Cache

I am trying to make use of Camel Cache for the first time. So I have created a small app based on camel-java maven archetype.
My code is based on the examples from here. Here is the snippet
public class AddingToCache extends RouteBuilder {
public void configure() {
from("direct:start")
.log("START")
.setHeader(CacheConstants.CACHE_OPERATION, constant(CacheConstants.CACHE_OPERATION_ADD))
.setHeader(CacheConstants.CACHE_KEY, constant("Custom_key"))
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
exchange.getOut().setBody("My custom out");
}
})
.log("starting ...")
.to("cache://cache1")
.to("direct:next");
}
}
public class ReadingFromCache extends RouteBuilder {
#Override
public void configure() throws Exception {
from("direct:next")
.setHeader(CacheConstants.CACHE_OPERATION, constant(CacheConstants.CACHE_OPERATION_GET))
.setHeader(CacheConstants.CACHE_KEY, constant("Custom_key"))
.to("cache://cache1")
.choice()
.when(header(CacheConstants.CACHE_ELEMENT_WAS_FOUND).isNotNull())
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
Object body = exchange.getIn().getBody();
System.out.println("Cache body - " + body);
}
})
.otherwise()
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
Object body = exchange.getIn().getBody();
System.out.println("Cache body when not found - " + body);
}
})
.end()
.to("direct:finish");
}
}
your routes are likely running, you just haven't invoked them yet (from the code you posted above anyways). you need to send a message to the direct:start or direct:next routes using a ProducerTemplate to exercise the routes...
ProducerTemplate template = camelContext.createProducerTemplate();
template.sendBody("direct:start", "message");

CometD publish a message back to a client

I am having a problem in sending back a message to a client. Below is my code
JavaScript
dojox.cometd.publish('/service/getservice', {
userid : _USERID,
});
dojox.cometd.subscribe('/service/getservice', function(
message) {
alert("abc");
alert(message.data.test);
});
Configuration Servlet
bayeux.createIfAbsent("/service/getservice", new ConfigurableServerChannel.Initializer() {
#Override
public void configureChannel(ConfigurableServerChannel channel) {
channel.setPersistent(true);
GetListener channelListner = new GetListener();
channel.addListener(channelListner);
}
});
GetListener class
public class GetListener implements MessageListener {
public boolean onMessage(ServerSession ss, ServerChannel sc) {
SomeClassFunction fun = new SomeClassFunction;
}
}
SomeClassFunction
class SomeClassFunction(){
}
here i am creating a boolean variable
boolean success;
if it is true send a message to client which is in javascript. how to send a message back to client. i have tried this line also.
remote.deliver(getServerSession(), "/service/getservice",
message, null);
but it is giving me an error on remote object and getServerSession method.
In order to reach your goal, you don't need to implement listeners nor to configure channels. You may need to add some configuration at a later stage, for example in order to add authorizers.
This is the code for the ConfigurationServlet, taken from this link:
public class ConfigurationServlet extends GenericServlet
{
public void init() throws ServletException
{
// Grab the Bayeux object
BayeuxServer bayeux = (BayeuxServer)getServletContext().getAttribute(BayeuxServer.ATTRIBUTE);
new EchoService(bayeux);
// Create other services here
// This is also the place where you can configure the Bayeux object
// by adding extensions or specifying a SecurityPolicy
}
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
{
throw new ServletException();
}
}
This is the code for EchoService class, taken fro this link:
public class EchoService extends AbstractService
{
public EchoService(BayeuxServer bayeuxServer)
{
super(bayeuxServer, "echo");
addService("/echo", "processEcho");
}
public void processEcho(ServerSession remote, Map<String, Object> data)
{
// if you want to echo the message to the client that sent the message
remote.deliver(getServerSession(), "/echo", data, null);
// if you want to send the message to all the subscribers of the "/myChannel" channel
getBayeux().createIfAbsent("/myChannel");
getBayeux().getChannel("/myChannel").publish(getServerSession(), data, null);
}
}

Categories

Resources