ProcessorImpl
package com.jxt.camelDemo;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.http.common.HttpMessage;
import org.apache.camel.util.json.JsonObject;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Map;
public class ProcessorImpl implements Processor {
public void process(Exchange exchange) throws Exception {
HttpServletRequest httpServletRequest = exchange.getIn().getBody(HttpServletRequest.class);
Map<String, String[]> parameterMap = httpServletRequest.getParameterMap();
System.out.println(parameterMap.toString());
HttpMessage message = (HttpMessage)exchange.getIn();
InputStream bodyStream = (InputStream)message.getBody();
String inputContext = this.analysisMessage(bodyStream);
bodyStream.close();
System.out.println(inputContext);
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD HH-mm-ss");
JsonObject jsonObject = new JsonObject();
jsonObject.put("errorCode",0);
jsonObject.put("msg","OK");
exchange.getMessage().setBody(jsonObject.toJson());
}
private String analysisMessage(InputStream bodyStream) throws IOException, IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] contextBytes = new byte[outStream.size()];
int realLen;
while((realLen = bodyStream.read(contextBytes , 0 ,outStream.size())) != -1) {
outStream.write(contextBytes, 0, realLen);
}
// 返回从Stream中读取的字串
try {
return new String(outStream.toByteArray() , "UTF-8");
} finally {
outStream.close();
}
}
}
MyRoute
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
public class MyRoute extends RouteBuilder {
public void configure() throws Exception {
from("timer://queryAward?period=5s&repeatCount=1")
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.to("http://39.98.60.120:5050/getJvmInfo").process(new ProcessorImpl())
.to("log:getJvmInfo?showExchangeId=false");
}
}
DemoMain
import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;
public class DemoMain {
public static void main(String[] args) throws Exception {
CamelContext context = new DefaultCamelContext();
MyRoute route = new MyRoute();
context.addRoutes(route);
context.start();
synchronized (DemoMain.class) {
DemoMain.class.wait();
}
context.stop();
}
}