Reputation: 177
Basically, I want to be able to post an object in JSON and print the details of this object using Java.
In order to o that I want (and I have to) use SPRING-BOOT and Camel
This is the class representing my object :
public class Response {
private long id;
private String content;
public Response(){
}
public Response(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content){
this.content = content;
}
}
Then I have a Rest Controller :
@RestController
public class BasicController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
//Handle a get request
@RequestMapping("/test")
public Response getResponse(@RequestParam(value="name", defaultValue="World") String name) {
System.out.println("Handle by spring");
return new Response(counter.incrementAndGet(),
String.format(template, name));
}
//Handle a post request
@RequestMapping(value = "/post", method = RequestMethod.POST)
public ResponseEntity<Response> update(@RequestBody Response rep) {
if (rep != null) {
rep.setContent("HANDLE BY SPRING");
}
return new ResponseEntity<Response>(rep, HttpStatus.OK);
}
}
With this code i'm able to handle a post request and print detail BUT I have to use Camel. So I tryed the following :
1) I added a bean conf
@SpringBootApplication
public class App
{
private static final String CAMEL_URL_MAPPING = "/camel/*";
private static final String CAMEL_SERVLET_NAME = "CamelServlet";
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
@Bean
public ServletRegistrationBean servletRegistrationBean() {
ServletRegistrationBean registration = new ServletRegistrationBean(new CamelHttpTransportServlet(), CAMEL_URL_MAPPING);
registration.setName(CAMEL_SERVLET_NAME);
return registration;
}
}
2) Then I created 2 routes.
<?xml version="1.0" encoding="UTF-8"?>
<routes xmlns="http://camel.apache.org/schema/spring">
<!-- <route id="test"> -->
<!-- <from uri="timer://trigger"/> -->
<!-- <to uri="log:out"/> -->
<!-- </route> -->
<route id="test2">
<from uri="servlet:///test"/>
<to uri="log:Handle by camel"/>
</route>
</routes>
With this I'm able to hand a request on camel. BUT I don't know how to make the link between Spring and camel. Is there a way to handle a request with my spring controller and then call a camel route? On the same URL..
Upvotes: 1
Views: 5025
Reputation: 8057
You can use autowired producerTemplate
to call Camel routes. It will be created if you add the dependency:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring-boot</artifactId>
<version>${camel.version}</version> <!-- use the same version as your Camel core version -->
</dependency>
For more info you can see Camel documentation here.
In your case you would call something like:
producerTemplate.sendBody...
Upvotes: 4