HTTP Router with Apache Camel
- 4 minutes read - 642 wordsThis article explains the http integration using Apache Camel. Create a configurable router to any http URL having place holders.
- Prerequisite
- Windows7, Eclipse Juno
- Java 1.7
Creating HTTP Router
Please follow below steps to generate POC for HTTP routing using apache camel.
Create Sample Camel Example
-
Create eclipse project using archetype “camel-archetype-spring”
mvn archetype:generate DarchetypeGroupId=com.tk.poc.camel -DarchetypeArtifactId=camel-archetype-spring -DarchetypeVersion=2.11.0 -DarchetypeRepository=https://repository.apache.org/content/groups/snapshots-group
-
Create following Java file
package com.tk.poc.camel; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.spring.Main; public class MyRouteBuilder extends RouteBuilder { /** * Allow this route to be run as an application */ public static void main(String[] args) throws Exception { new Main().run(); } public void configure() { } }
-
pom.xml
– add following dependencies<dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-http</artifactId> <version>2.11.0</version> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-stream</artifactId> <version>2.11.0</version> </dependency>
-
Clean up src/main/resources/META-INF/spring/
camel-context.xml
<camel:camelContext xmlns="http://camel.apache.org/schema/spring"> <camel:package>com.nagarro.jsag.poc.camel</camel:package> </camel:camelContext>
-
Run
mvn eclipse:eclipse
to include dependencies in class path of eclipse.mvn eclipse:eclipse
Create Command Configurations
-
Let’s configure commands in a file in following format Commands will to be defined in a text file where every line of text file represents a command in following format:
<command-key>###<number of placeholders>###<URL with placeholders if any in format “{index of placeholder starting from 0}”>
commands.txt
start###0###http://localhost:8081/home-page/poc.jsp search###1###http://localhost:8081/home-page/poc.jsp?search={0} clean###0###http://localhost:8081/home-page/logout.jsp
-
Change the
Main
method ofMyRouteBuilder.java
private static Map<String, String> commandMap = new HashMap<String, String>(); private static StringBuilder commandText = new StringBuilder("Commands:\n"); public static void main(String[] args) throws Exception { String filePath = "./commands.txt"; if(args.length>0){ filePath = args[0]; } try (FileReader fileReader = new FileReader(filePath); BufferedReader reader = new BufferedReader(fileReader);) { String line = reader.readLine(); while (line != null) { String[] keyVal = line.split("###"); commandMap.put(keyVal[0], keyVal[2]); commandText.append("\t").append(keyVal[0]); if(!"0".equals(keyVal[1])){ commandText.append(" (require ").append(keyVal[1]).append(" parameter)"); } commandText.append("\n"); line = reader.readLine(); } commandText.append("\texit"); commandText.append("\nEnter command and required parameters:"); } new Main().run(); }
Configure the Camel Routes
We will configure routes such as we take input (command) from console and then fetch the http URL associated to the command and then route to http URL, route the response to console as well as a log file. Define configure method as follows:
public void configure() {
from("stream:in?promptMessage=" + URLEncoder.encode(commandText.toString())).process(new
Processor() {
@Override
public void process(Exchange exchange) throws Exception {
String input = exchange.getIn().getBody(String.class);
boolean success = true;
if (input.trim().length() > 0) {
if("exit".equals(input)){
System.exit(0);
}
String[] commandAndParams = input.split(" ");
url = commandMap.get(commandAndParams[0]);
if (url != null) {
if (commandAndParams.length > 1) {
String [] params = Arrays.copyOfRange(commandAndParams, 1,
commandAndParams.length);
url = MessageFormat.format(url, (Object[])params);
}
exchange.getOut().setHeader(Exchange.HTTP_URI, url);
} else {
success = false;
}
} else {
success = false;
}
if (!success) {
throw new Exception("Error in input");
}
}
}).to("http://localhost:99/").process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
StringBuffer stringBuffer = new StringBuffer("\n\nURL :" + url);
stringBuffer.append("\n\nHeader :\n");
Map<String, Object> headers = exchange.getIn().getHeaders();
for (String key : headers.keySet()) {
if (!key.startsWith("camel")) {
stringBuffer.append(key).append("=")
.append(headers.get(key)).append("\n");
}
}
String body = exchange.getIn().getBody(String.class);
stringBuffer.append("\nBody:\n" + body);
exchange.getOut().setBody(stringBuffer.toString());
exchange.getOut().setHeader(Exchange.FILE_NAME,
constant("response.txt"));
}
}).to("file:.?fileExist=Append").to("stream:out");
}
Export as runnable jar
Right click on the project and export an runnable jar. name it http.jar
Run the example
- Run command
“java -jar http.jar <commands file path>”
, if you don’t specify commands files will automatically pick the “commands.txt
” from same folder and display following
D:\HTTPClient>java -jar http.jar
Commands:
start
menu (require 1 parameter)
clean
exit
Enter command and required parameters:
- Enter command “start”
Enter command and required parameters:start
URL : http://localhost:8081/home-page/poc.jsp
Header :
…
Body:
..
Commands:
start
search (require 1 parameter)
clean
exit
Enter command and required parameters:
- Enter command “Menu with choice”
Enter command and required parameters:search IBM
URL : http://localhost:8081/home-page/poc.jsp?search=IBM
Header :
…
Body:
…
Commands:
start
menu (require 1 parameter)
clean
exit
Enter command and required parameters:
- You may continue seeing the menu or may call clean or exit
Enter command and required parameters:clean
URL : http://localhost:8081/home-page/logout.jsp
…
Enter command and required parameters:exit
D:\Ericsson\HTTPClient>
Conclusion
We have developed the Router using camel and same can directly be utilized in the project.
#java #Apache Camel #enterprise #integration #technology