最新基于Json 协议的架构

package util;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.map.ObjectMapper;

public class Test {
	private static ObjectMapper mapper = new ObjectMapper();

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Map<String, Object> p = new HashMap<String, Object>();
		p.put("username", "rzy阮智勇");
		p.put("pwd", "111111");
		Object result = call("PmsService.test", p, 1, 5);
		System.out.println("===" + result);
	}

	public static Object call(String sid, Object... args) {
		String url = "http://localhost:8080/PMS/handler";
		String result = null;
		HttpClient client = new DefaultHttpClient();
		try {

			HttpPost post = new HttpPost(url);
			post.addHeader("api", sid);
			StringEntity s = new StringEntity(mapper.writeValueAsString(args),
					"UTF-8");
			s.setContentType("application/json");
			post.setEntity(s);

			HttpResponse res = client.execute(post);
			if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = res.getEntity();
				result = EntityUtils.toString(entity);
			}
		} catch (Exception e) {
			throw new RuntimeException("请求失败", e);
		} finally {
			client.getConnectionManager().shutdown();
		}
		return result;
	}

}
package util;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;

@SuppressWarnings("serial")
public class Handler extends HttpServlet
{
    ServletContext context;
    static ObjectMapper mapper = new ObjectMapper();
    static Logger log = Logger.getLogger(Handler.class);

    @Override
    public void init(ServletConfig config) throws ServletException
    {
        this.context = config.getServletContext();
        super.init(config);
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException
    {
        ServiceContext sc = ServiceContext.begin(this.context, request, response);
        response.setContentType("application/json;charset=utf-8");
        Object result = null;
        String api = request.getHeader("api");
        String url = request.getRequestURI();
        Object[] args = mapper.readValue(request.getInputStream(), Object[].class);
        String className = StringUtils.substringBeforeLast(api, ".");
        String methodName = StringUtils.substringAfterLast(api, ".");
        String packageName = StringUtils.substringAfterLast(url, "/");
        log.debug("api==>" + api);
        for (int i = 0, len = args.length; i < len; i++)
        {
            log.debug("Parameter" + i + "==>" + args[i]);
        }
        try
        {
            Class cls = Class.forName(packageName + "." + className);

            if (args.length > 0)
            {
                Class[] parameterTypes = new Class[args.length];

                for (int i = 0, j = args.length; i < j; i++)
                {
                    parameterTypes[i] = args[i].getClass();
                }
                result = MethodUtils.invokeMethod(ServiceFactory.getService(cls), methodName, args, parameterTypes);
            }
            else
            {
                result = MethodUtils.invokeMethod(ServiceFactory.getService(cls), methodName, null);
            }

            if (result != null)
            {
                log.debug("Result==>" + result);
                mapper.writeValue(response.getWriter(), result);
            }
        }
        catch (ClassNotFoundException e)
        {

            log.debug("Exception in service.");
            log.debug("service未发现" + e.getCause().getMessage());
        }
        catch (NoSuchMethodException e)
        {

            log.debug("Exception in service.");
            log.debug("service对应的方法未发现" + e.getMessage());
        }
        catch (InvocationTargetException e)
        {

            log.debug("Exception in service.");
            Throwable t = e.getCause();
            if (t instanceof DataAccessException)
            {
                String error = "database exception." + t.getMessage();
                mapper.writeValue(response.getWriter(), error);
                log.debug(error);
            }
            else
            {
                log.debug(t.getMessage());
            }
        }
        catch (Exception e)
        {

            log.debug("Exception in service." + e.getCause().getMessage());
        }
        finally
        {
            if (sc != null)
            {
                sc.end();
            }
        }
    }
}
package util;

import java.lang.reflect.Method;
import java.util.regex.Pattern;

import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.CallbackFilter;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import net.sf.cglib.proxy.NoOp;

import org.apache.log4j.Logger;

public class ServiceFactory
{

    static Logger log = Logger.getLogger(ServiceFactory.class);

    static MethodInterceptor interceptor = new MethodInterceptor()
    {
        public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable
        {
            Object result = null;
            try
            {
                log.debug("事务开始");
                DBUtils.beginTransaction();
                result = methodProxy.invokeSuper(obj, args);
                log.debug("事务提交");
                DBUtils.commitTransaction();
                
                
                StringBuffer logs = new StringBuffer();
                String api = ServiceContext.getHeader("api");
                String username = ServiceContext.getHeader("username");
                String ip = ServiceContext.getIP();
                String time = Utils.now("yyyy-MM-dd HH:mm:ss");
                logs.append(username).append("|");
                logs.append(ip).append("|");
                logs.append(time).append("|");
                logs.append(api).append("|");
                logs.append(1).append("|");
                logs.append("memo");
                LogHandler.put(logs.toString());
            }
            catch (Exception e)
            {
                log.debug("事务回滚");
                DBUtils.rollbackTransaction();
                throw e;
            }
            return result;
        }
    };

    static CallbackFilter filter = new CallbackFilter()
    {
        public int accept(Method arg0)
        {
            return Pattern.compile("^(add|del|mod|set|reg|active|cancel)").matcher(arg0.getName()).find() ? 0 : 1;
        }
    };

    @SuppressWarnings("unchecked")
    public static <T> T getService(Class<T> cls)
    {
        try
        {
            Enhancer en = new Enhancer();
            en.setSuperclass(cls);
            en.setCallbacks(new Callback[] { interceptor, NoOp.INSTANCE });
            en.setCallbackFilter(filter);
            return (T) en.create();
        }
        catch (Exception e)
        {
            log.debug("Create " + cls.getSimpleName() + " Failure!");
            e.printStackTrace();
            return null;
        }
    }
}

  

相关推荐