NC servlet内置TOKEN 默认用户等

package nc.pub.servlet;

import com.alibaba.fastjson.JSON;
import com.thoughtworks.xstream.XStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.security.SecureRandom;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nc.bs.framework.adaptor.IHttpServletAdaptor;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.common.RuntimeEnv;
import nc.bs.framework.server.ISecurityTokenCallback;
import nc.bs.logging.Logger;
import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.processor.ResultSetProcessor;
import nc.vo.pub.BusinessException;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

public class ApiServlet
  extends HttpServlet
  implements IHttpServletAdaptor
{
  private static final long serialVersionUID = 3269572064362355136L;
  private String userid = "NC_USER0000000000000";
  private String datasource = "design";
  private String groupId = "";
  private HttpServletResponse response = null;
  
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    doAction(request, response);
  }
  
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    doAction(request, response);
  }
  
  public void doAction(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    this.response = response;
    
    ServletIPConfig config = loadConfigured();
    if (config == null)
    {
      responseErrorMsg("配置文件为空");
      return;
    }
    this.datasource = config.getDataSource();
    this.groupId = config.getGroupID();
    List<String> ips = config.getIpList();
    if ((ips == null) || (ips.size() <= 0))
    {
      responseErrorMsg("ip白名单没有配置");
      return;
    }
    String ip = request.getRemoteHost();
    if (!ips.contains(ip))
    {
      responseErrorMsg("ip地址没有在白名单中");
      return;
    }
    String sql = request.getParameter("sql");
    if (StringUtils.isEmpty(sql))
    {
      responseErrorMsg("查询语句为空");
      return;
    }
    sql = URLDecoder.decode(sql, "UTF-8");
    byte[] sqlbytes = sql.getBytes();
    if (Base64.isArrayByteBase64(sqlbytes))
    {
      Base64 base64 = new Base64();
      sql = new String(base64.decode(sqlbytes), "UTF-8");
    }
    else
    {
      responseErrorMsg("查询语句没有进行base64编码");
      return;
    }
    setInfo();
    setToken();
    Object data = getDatas(sql);
    if (data == null)
    {
      responseErrorMsg("没有获取到数据");
      return;
    }
    if ((data instanceof String))
    {
      responseErrorMsg(data.toString());
      return;
    }
    ResultModel result = new ResultModel();
    result.setSuccess(Boolean.valueOf(true));
    result.setMsg("查询成功");
    result.setData(data);
    responseMsg(JSON.toJSONString(result));
  }
  
  public Object getDatas(String sql)
  {
    if (StringUtils.isEmpty(sql)) {
      return null;
    }
    try
    {
      getQuyerService().executeQuery(sql, new ResultSetProcessor()
      {
        public Object handleResultSet(ResultSet rs)
          throws SQLException
        {
          List results = new ArrayList();
          while (rs.next())
          {
            ResultSetMetaData metaData = rs.getMetaData();
            int cols = metaData.getColumnCount();
            Map<String, Object> rsValues = new HashMap();
            for (int i = 1; i <= cols; i++)
            {
              Object value = rs.getObject(i);
              if ((value instanceof BigDecimal)) {
                value = ((BigDecimal)value).toPlainString();
              }
              String propName = metaData.getColumnLabel(i).toLowerCase();
              if (propName == null) {
                propName = metaData.getColumnName(i).toLowerCase();
              }
              rsValues.put(propName, value);
            }
            results.add(rsValues);
          }
          return results;
        }
      });
    }
    catch (BusinessException e)
    {
      Logger.error("客户端调用错误:数据库执行异常" + e.getMessage());
      return "客户端调用错误:数据库执行异常" + e.getMessage();
    }
  }
  
  public void responseMsg(String contentType, String content)
  {
    this.response.setContentType(contentType);
    this.response.setCharacterEncoding("UTF-8");
    try
    {
      this.response.getWriter().write(content);
    }
    catch (IOException e)
    {
      Logger.error("客户端调用错误:" + e.getMessage());
      ExceptionUtils.wrappBusinessException("客户端调用错误:" + e.getMessage());
    }
  }
  
  public void responseMsg(String content)
  {
    String contentType = "application/json";
    responseMsg(contentType, content);
  }
  
  public void responseErrorMsg(String content)
  {
    String contentType = "application/json";
    ResultModel result = new ResultModel();
    result.setSuccess(Boolean.valueOf(false));
    result.setMsg(content);
    responseMsg(contentType, JSON.toJSONString(result));
  }
  
  private void setToken()
  {
    SecureRandom rand = new SecureRandom();
    byte sysid = InvocationInfoProxy.getInstance().getSysid();
    ISecurityTokenCallback sc = (ISecurityTokenCallback)NCLocator.getInstance().lookup(ISecurityTokenCallback.class);
    byte[] bytes = new byte[64];
    rand.nextBytes(bytes);
    try
    {
      sc.token((sysid + ":" + this.userid).getBytes("UTF-8"), bytes);
    }
    catch (UnsupportedEncodingException e)
    {
      e.printStackTrace();
    }
  }
  
  private void setInfo()
  {
    InvocationInfoProxy proxy = InvocationInfoProxy.getInstance();
    proxy.setUserId(this.userid);
    proxy.setUserDataSource(this.datasource);
    proxy.setGroupId(this.groupId);
  }
  
  public IUAPQueryBS getQuyerService()
  {
    return (IUAPQueryBS)NCLocator.getInstance().lookup(IUAPQueryBS.class);
  }
  
  private ServletIPConfig loadConfigured()
  {
    String fileName = "servlet-ip-config.xml";
    String fullName = RuntimeEnv.getInstance().getNCHome() + "/ierp/bin/" + fileName;
    
    XStream xs = new XStream();
    xs.alias("servletConfig", ServletIPConfig.class);
    xs.alias("ip", String.class);
    ServletIPConfig config = null;
    try
    {
      config = (ServletIPConfig)xs.fromXML(new InputStreamReader(new FileInputStream(fullName), "utf-8"));
    }
    catch (Exception e)
    {
      Logger.error("客户端调用:" + e.getMessage());
      ExceptionUtils.wrappBusinessException(e.getMessage());
    }
    return config;
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值