XUtil

package util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletContext;

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.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.caucho.hessian.client.HessianProxyFactory;

public class XUtil
{
    static Logger log = Logger.getLogger(XUtil.class);
    static Properties prop = new Properties();
    static
    {
        try
        {
            InputStream is = XUtil.class.getClassLoader().getResourceAsStream("services.properties");
            prop.load(is);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public static Object call(String sid, Object... params)
    {
        HessianProxyFactory factory = new MyHessianProxyFactory();
        Object result = null;
        try
        {
            factory.setHessian2Reply(true);
            factory.setChunkedPost(false);
            Call caller = (Call) factory.create(Call.class, prop.getProperty("url"));
            result = caller.call(sid, params);
        }
        catch (Exception e)
        {
            log.debug(e.getCause().getMessage());
        }
        return result;
    }

    public static Object call2(String sid, Object... args)
    {
        String url = "http://localhost:8080/ss/handler";
        String result = null;
        ThreadSafeClientConnManager threadSafeClientConnManager = new ThreadSafeClientConnManager();
        HttpClient client = new DefaultHttpClient(threadSafeClientConnManager);
        client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
        try
        {
            HttpPost post = new HttpPost(url);
            post.addHeader("api", sid);
            post.addHeader("username", ((Map<String, Object>) getUser()).get("username").toString());
            System.out.println(JSON.toJSONString(args));
            StringEntity s = new StringEntity(JSON.toJSONString(args), "UTF-8");
            s.setContentType("application/json");
            post.setEntity(s);

            HttpResponse res = client.execute(post);
            HttpEntity entity = res.getEntity();
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                result = EntityUtils.toString(entity);
            }
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND)
            {
                throw new RuntimeException("请求未发现");
            }
            if (res.getStatusLine().getStatusCode() == 9999)
            {
                String kk = EntityUtils.toString(entity);
                throw new RuntimeException(kk);
            }
        }
        catch (Exception e)
        {
            throw new RuntimeException(e.getMessage());
        }
        finally
        {
            client.getConnectionManager().shutdown();
        }
        return result;
    }

    public static void calljson(String sid, Object... args)
    {
        toJSON(call(sid, args));
    }

    public static void call2json(String sid, Object... args)
    {
        toJSON(call2(sid, args));
    }

    public static void toJSON(Object obj)
    {
        RequestContext.getResponse().setContentType("text/javascript;charset=UTF-8");
        try
        {
            RequestContext.getResponse().getWriter().print(JSON.toJSONString(obj));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static Map<String, Object> getParameterMap()
    {
        Map<String, Object> map = new HashMap<String, Object>();
        Enumeration<?> em = RequestContext.getRequest().getParameterNames();
        while (em.hasMoreElements())
        {
            String k = (String) em.nextElement();
            String v = RequestContext.getRequest().getParameter(k);
            map.put(k, v);
        }
        return map;
    }

    public static String getParameter(String name)
    {
        return RequestContext.getRequest().getParameter(name);
    }

    public static Object getUser()
    {
        return RequestContext.getSession().getAttribute("user");
    }

    public static String getIP()
    {
        return RequestContext.getRequest().getRemoteAddr();
    }

    @SuppressWarnings("unchecked")
    public static List<Map<String, Object>> toList(String str)
    {
        List<Map<String, Object>> data = null;
        try
        {
            data = (List<Map<String, Object>>) JSON.parseObject(str, List.class);
        }
        catch (Exception e)
        {
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
        return data;
    }

    public static void ok()
    {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", true);
        result.put("msg", null);
        toJSON(result);
    }

    public static void ok(String msg, Object... args)
    {
        // ResourceBundle rb = ResourceBundle.getBundle("resource", Locale.getDefault(), RequestContext.class
        // .getClassLoader());
        // String msg = rb.getString(code);
        // msg = (msg != null) ? MessageFormat.format(msg, args) : code;
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", true);
        result.put("msg", msg);
        try
        {
            RequestContext.getResponse().getWriter().write(JSON.toJSONString(result));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void error(String msg, Object... args)
    {
        // ResourceBundle rb = ResourceBundle.getBundle("resource", Locale.getDefault(), RequestContext.class
        // .getClassLoader());
        // String msg = rb.getString(code);
        // msg = (msg != null) ? MessageFormat.format(msg, args) : code;
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", false);
        result.put("msg", msg);
        try
        {
            RequestContext.getResponse().getWriter().write(JSON.toJSONString(result));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void attr(String key, Object value, String scope)
    {
        if ("application".equals(scope))
        {
            RequestContext.getServletContext().setAttribute(key, value);
        }
        else if ("session".equals(scope))
        {
            RequestContext.getSession().setAttribute(key, value);
        }
        else
        {
            RequestContext.getRequest().setAttribute(key, value);
        }
    }

    public static Object attr(String key, String scope)
    {
        if ("application".equals(scope))
        {
            return RequestContext.getServletContext().getAttribute(key);
        }
        else if ("session".equals(scope))
        {
            return RequestContext.getSession().getAttribute(key);
        }
        else
        {
            return RequestContext.getRequest().getAttribute(key);
        }
    }

    public static void redirect(String url)
    {
        RequestContext.redirect(url);
    }

    public static void forward(String url)
    {
        RequestContext.forward(url);
    }

    public static void invalidate()
    {
        RequestContext.invalidate();
    }

    public static OutputStream getOutputStream()
    {
        try
        {
            return RequestContext.getResponse().getOutputStream();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public static ServletContext getServletContext(){
        return RequestContext.getServletContext();
    }
}

interface Call
{
    public Object call(String sid, Object... args);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
rzy
06-08 613

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值