Getting invalid characters in camel route exchange body() - java

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

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")

Apache Camel test expectedBodiesReceived check if the body is null?

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();

Routing websocket destination in Spring-boot

Having raw websocket implementation:
#Configuration
#EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MessageHandler(), "/websocket")
.setAllowedOrigins("*")
.addInterceptors();;
}
}
Handler:
public class MessageHandler extends TextWebSocketHandler {
#Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
// The WebSocket has been closed
}
#Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
String auth = (String) session.getAttributes().get("auth");
System.out.println(auth);
session.sendMessage(new TextMessage("You are now connected to the server. This is the first message."));
}
#Override
protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {
// A message has been received
}
}
The websocket client connect to server ( handshake etc. ) with /websocket url e.g ws://localhost:8080/websocket
However, now that connection is estabilished is there a way how to route messages? Lets say i have app that provides chat and some pop-up functionality ( for simplicity lets say the user sends pop-up message and some pop-up window shows to all of his friends in app ).
Ofcourse i would like to route chat messages to /chat and popup to /popup.
One way how to achieve this is to send json message to server and parse it there e.g:
protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {
String path = getRouteFromJsonMessage(textMessage);
if( ! "".equals(path) && path.equals("chat")
....
if( ! "".equals(path) && path.equals("popup")
....
}
But this seems too slow, parsing json on every message. Is there some other, better way how to achieve routing?
Thanks for help!
Why don't you just register two different MessageHandlers
public class WebSocketConfig implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new ChatMessageHandler(), "/chat")
.setAllowedOrigins("*")
.addInterceptors()
.addHandler(new PopUpHandler(), "/popup") //etc;
}
}

Apache Camel and read-only message queue

So I'm using the SQS combined with Apache Camel. Some messages have references to s3 object. I need to route this messages to another queue, but the problem is that I have to process associated with this message s3 object without message modification.
The workflow is
Get message with body["ref":"some-ref"] from queue-1
Get S3 object associated with the message.
If s3 object contains option pass the message to queue-2
If s3 object doesn't contain option pass the message to queue-3.
And I faced with the problem that .process method modify message body.
from("queue-1")
.choice()
.when(header("option").isNotNull())
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
//FETCH S3 OBJECT }
})
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
//CHECK IF OBJECT HAS SOME OPTIONS
}
}).to("queue-2")
.when(header("option").isNull())
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
//CHECK IF BODY HAS SOME OPTIONS
}
}).to("queue-3)
.otherwise()
.log("Unknown");
So Is there a solution that can store message without modifying it?

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");

Categories

Resources