---
title: "Camel Bean的简单例子"
author: "白云天"
date: "2016-05-10T15:15:22Z"
tags: []
categories: ["开源软件"]
slug: "camel-bean"
draft: false
lastmod: "2016-05-10T15:15:22Z"
id: 2297180
url: "https://iwin.iteye.com/blog/2297180"
---

**web.xml**

 

&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;  
&lt;web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"  
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app\_2\_4.xsd"&gt;

  &lt;display-name&gt;My Web Application&lt;/display-name&gt;

  &lt;!-- location of spring xml files --&gt;  
  &lt;context-param&gt;  
    &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;  
    &lt;param-value&gt;classpath:camel-config.xml&lt;/param-value&gt;  
  &lt;/context-param&gt;

  &lt;!-- the listener that kick-starts Spring --&gt;  
  &lt;listener&gt;  
    &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;  
  &lt;/listener&gt;

  &lt;!-- Camel servlet --&gt;  
  &lt;servlet&gt;  
    &lt;servlet-name&gt;CamelServlet&lt;/servlet-name&gt;  
    &lt;servlet-class&gt;org.apache.camel.component.servlet.CamelHttpTransportServlet&lt;/servlet-class&gt;  
    &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;  
  &lt;/servlet&gt;

  &lt;!-- Camel servlet mapping --&gt;  
  &lt;servlet-mapping&gt;  
    &lt;servlet-name&gt;CamelServlet&lt;/servlet-name&gt;  
    &lt;url-pattern&gt;/camel/\*&lt;/url-pattern&gt;  
  &lt;/servlet-mapping&gt;

&lt;/web-app&gt;

 

**camel-config.xml**

 

&lt;?xml version="1.0" encoding="UTF-8"?&gt;  
   
&lt;beans xmlns="http://www.springframework.org/schema/beans"  
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
       xmlns:camel="http://camel.apache.org/schema/spring"  
       xsi:schemaLocation="  
         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
         http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"&gt;  
   
  &lt;bean id="testBean" class="com.suneee.common.TestBean"/&gt;

  &lt;camelContext id="x1" xmlns="http://camel.apache.org/schema/spring"&gt;  
    &lt;route id="helloRoute"&gt;  
      &lt;!-- incoming requests from the servlet is routed --&gt;  
      &lt;from uri="servlet:hello"/&gt;  
      &lt;choice&gt;  
        &lt;when&gt;  
          &lt;header&gt;name&lt;/header&gt;  
          &lt;transform&gt;  
            &lt;simple&gt;Hi I am ${sysenv.HOSTNAME}. Hello ${header.name} how are you today?&lt;/simple&gt;  
          &lt;/transform&gt;  
        &lt;/when&gt;  
        &lt;otherwise&gt;  
          &lt;transform&gt;  
            &lt;constant&gt;Add a name parameter to uri, eg ?name=foo&lt;/constant&gt;  
          &lt;/transform&gt;  
        &lt;/otherwise&gt;  
      &lt;/choice&gt;  
    &lt;/route&gt;  
  &lt;/camelContext&gt;

  &lt;camelContext id="x2" xmlns="http://camel.apache.org/schema/spring"&gt;  
    &lt;route id="helloRoute"&gt;  
      &lt;!-- incoming requests from the servlet is routed --&gt;  
      &lt;from uri="servlet:show"/&gt;  
      &lt;!--  
      &lt;to uri="bean:testBean?method=readBody(${body})"/&gt;  
      --&gt;  
      &lt;!--  从 Message / Exchange.getIn() 读取 body --&gt;  
      &lt;to uri="bean:testBean?method=showBody(\*)"/&gt;  
       
      &lt;!--  从 Message / Exchange.getIn() 构造 Request 对象 --&gt;  
      &lt;to uri="bean:testBean?method=parseRequest(\*,${body})"/&gt;

      &lt;!--  处理  Request 对象, 返回 生产 html 内容 的 主要数据 --&gt;  
      &lt;to uri="bean:testBean?method=process(${body})"/&gt;   
      
      &lt;!--  更加主要数据 生成 html 内容 --&gt;  
      &lt;to uri="bean:testBean?method=toHtml(${body})"/&gt;  
     
      &lt;!-- 输出内容 通过 Exchange 进行输出 html 内容, 设置 http-head --&gt;  
      &lt;to uri="bean:testBean?method=response(\*,${body})"/&gt;

      &lt;!--直接返回 html 内容,将会输出到 http客户端  
      &lt;to uri="bean:testBean?method=toHtml(${body})"/&gt;  
      --&gt;

      &lt;!--  
      &lt;process ref="helloProcessor"/&gt;  
      --&gt;  
    &lt;/route&gt;  
  &lt;/camelContext&gt;

&lt;/beans&gt;

 

import java.io.ByteArrayInputStream;  
import java.util.Date;  
import java.util.Map;

import org.apache.camel.Exchange;  
import org.apache.camel.Message;

public class TestBean {  
     
    public TestBean(){  
        super();  
    }  
     
    public String readBody(Object body) throws Exception {  
        System.out.println("readBody--&gt;"+body);  
        byte \[]bs=read((ByteArrayInputStream)body);   
        String msg=new String(bs,"utf-8");  
        System.out.println("Input="+msg);  
        return msg;  
    }  
     
    public String showBody(Message in) throws Exception {   
        byte \[]bs=read((ByteArrayInputStream)in.getBody());   
        String msg=new String(bs,"utf-8");  
        System.out.println("showBody--&gt;"+msg);   
        return msg;  
    }  
     
    private byte\[] read(ByteArrayInputStream in){  
        int len=in.available();  
        byte \[]data=new byte\[len];  
        in.read(data,0,data.length);  
        return data;  
    }  
     
    public Request parseRequest(Message in,String body) {  
        Map&lt;String, Object&gt; ms=in.getHeaders();  
        Request r=new Request();  
        r.setHead(ms);  
        System.out.println("parseRequest--&gt; heads="+ms+",body="+body);  
        r.setBody(body);  
        return r;  
    }  
     
    public  Object process(Request req) {  
        System.out.println("process--&gt; heads="+req.getHead()+",body="+req.getBody());  
        String s="你好，系统时间为："+new Date();  
        return s;  
    }  
    public  void response(Exchange out,String html) {  
        System.out.println("setHeads--&gt;");   
        //out.getOut().setHeader(Exchange.CONTENT\_TYPE, "text/html" + "; charset=utf-8");  
        out.getOut().setHeader(Exchange.CONTENT\_TYPE, "application/octet-stream" + "; charset=utf-8");   
        out.getOut().setBody(html);  
    }  
     
    public  String toHtml(Object r) {  
        System.out.println("toHtml--&gt; object="+r);   
        return String.valueOf(r);  
    }  
     
     
}

import java.io.BufferedReader;  
import java.io.InputStreamReader;  
import java.io.PrintWriter;  
import java.net.URL;  
import java.net.URLConnection;

public class TestHttp {

    public static void main(String\[] args) throws Exception {  
        String to = "http://127.0.0.1:8080/esb/camel/show";  
        String param="name=中国&sex=100&date=20178091&rid=make\_id\_001";  
         
        URL url = new URL(to);  
        PrintWriter out = null;  
        BufferedReader in = null;  
        String result = "";

        // 打开和URL之间的连接  
        URLConnection conn = url.openConnection();  
        // 设置通用的请求属性  
        conn.setRequestProperty("accept", "\*/\*");  
        conn.setRequestProperty("connection", "Keep-Alive");  
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");  
        // 发送POST请求必须设置如下两行  
        conn.setDoOutput(true);  
        conn.setDoInput(true);  
        // 获取URLConnection对象对应的输出流  
        out = new PrintWriter(conn.getOutputStream());  
        // 发送请求参数  
        out.print(param);  
        // flush输出流的缓冲  
        out.flush();  
        // 定义BufferedReader输入流来读取URL的响应  
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));  
        String line;  
        while ((line = in.readLine()) != null) {  
            result += line;  
        }  
        System.out.println(result);  
    }  
}