Bladeren bron

上传文件

陈士柏 4 jaren geleden
bovenliggende
commit
4bf7df281a
100 gewijzigde bestanden met toevoegingen van 10897 en 0 verwijderingen
  1. 41 0
      Admin.java
  2. 76 0
      AuthenticationInterceptor.java
  3. 133 0
      Base64.java
  4. 230 0
      Build.java
  5. 77 0
      Build_elec.java
  6. 60 0
      Build_water.java
  7. 31 0
      CharacterEncodingFilter.java
  8. 21 0
      Clien_test.java
  9. 198 0
      CodeUtil.java
  10. 50 0
      Config.java
  11. 10 0
      ConfigDao.java
  12. 39 0
      ConfigDaoImpl.java
  13. 10 0
      ConfigService.java
  14. 29 0
      ConfigServiceImpl.java
  15. 98 0
      ConstDefault.java
  16. 169 0
      Consume.java
  17. 28 0
      ConsumeDao.java
  18. 162 0
      ConsumeDaoImpl.java
  19. 28 0
      ConsumeService.java
  20. 63 0
      ConsumeServiceImpl.java
  21. 65 0
      CreateSign1.java
  22. 250 0
      DBtoExcel.java
  23. 50 0
      Data.java
  24. 394 0
      DataClient.java
  25. 113 0
      Detail_elc.java
  26. 50 0
      Detail_elc2.java
  27. 50 0
      Device.java
  28. 12 0
      DictionaryCompare.java
  29. 68 0
      ET.java
  30. 525 0
      Elec.java
  31. 55 0
      ElecDao.java
  32. 312 0
      ElecDaoImpl.java
  33. 61 0
      ElecService.java
  34. 228 0
      ElecServiceImpl.java
  35. 23 0
      ElecTotal.java
  36. 51 0
      EndPay.java
  37. 41 0
      ErrorWaterPay.java
  38. 28 0
      GetHttpParam.java
  39. 18 0
      GloablExceptionHandler.java
  40. 34 0
      Globals.java
  41. 32 0
      HistoryBm.java
  42. 350 0
      HttpClientHelper.java
  43. 277 0
      HttpUtil.java
  44. 200 0
      HttpUtils.java
  45. 487 0
      HttpsClient.java
  46. 390 0
      HttpsUtil.java
  47. 23 0
      InterceptorConfig.java
  48. 164 0
      JaxbUtil.java
  49. 56 0
      JsonUtil.java
  50. 26 0
      LeyouCorsConfig.java
  51. 95 0
      Login.java
  52. 52 0
      LoginFilter.java
  53. 2 0
      MANIFEST.MF
  54. 49 0
      MD5Utils.java
  55. 34 0
      MyDate.java
  56. 23 0
      MyX509TrustManager.java
  57. 63 0
      OnlineTime.java
  58. 12 0
      PassToken.java
  59. 76 0
      Pay.java
  60. 275 0
      PayResult.java
  61. 128 0
      PayWxUtil.java
  62. 61 0
      Price.java
  63. 23 0
      Propel.java
  64. 30 0
      PropelDao.java
  65. 186 0
      PropelDaoImpl.java
  66. 30 0
      PropelService.java
  67. 57 0
      PropelServiceImpl.java
  68. 408 0
      Propelling.java
  69. 37 0
      QueryUrlEnum.java
  70. 124 0
      Recharge.java
  71. 31 0
      RechargeDao.java
  72. 191 0
      RechargeDaoImpl.java
  73. 31 0
      RechargeService.java
  74. 57 0
      RechargeServiceImpl.java
  75. 131 0
      Recharge_elc.java
  76. 53 0
      ResUtil.java
  77. 52 0
      ResponseUtil.java
  78. 86 0
      ResultStatusCode.java
  79. 103 0
      ResultUtil.java
  80. 42 0
      SHA1.java
  81. 845 0
      StringUtil.java
  82. 272 0
      TLinx2Util.java
  83. 49 0
      TLinxAESCoder.java
  84. 43 0
      TLinxMD5.java
  85. 46 0
      TLinxMapUtil.java
  86. 34 0
      TLinxSHA1.java
  87. 57 0
      Test.java
  88. 37 0
      TestParams.java
  89. 130 0
      TimeExchange.java
  90. 21 0
      TokenUtil.java
  91. 84 0
      TongYiReturn.java
  92. 137 0
      Upload.java
  93. 163 0
      User.java
  94. 30 0
      UserDao.java
  95. 170 0
      UserDaoImpl.java
  96. 12 0
      UserLoginToken.java
  97. 31 0
      UserService.java
  98. 84 0
      UserServiceImpl.java
  99. 124 0
      Users.java
  100. 0 0
      Water.java

+ 41 - 0
Admin.java

@@ -0,0 +1,41 @@
+package com.happy.Model;
+
+public class Admin {
+
+    public int id;
+    public String name;
+    public String number;
+    public String password;
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getNumber() {
+        return number;
+    }
+
+    public void setNumber(String number) {
+        this.number = number;
+    }
+
+    public String getPassword() {
+        return password;
+    }
+
+    public void setPassword(String password) {
+        this.password = password;
+    }
+}

+ 76 - 0
AuthenticationInterceptor.java

@@ -0,0 +1,76 @@
+package com.happy.interceptor;
+
+import com.alibaba.fastjson.JSONObject;
+import com.happy.Model.Login;
+import com.happy.Until.ResultUtil;
+import com.happy.Until.TokenUtil;
+import com.happy.annotation.PassToken;
+import com.happy.annotation.UserLoginToken;
+import com.happy.constant.ResultStatusCode;
+import com.happy.service.UserService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.method.HandlerMethod;
+import org.springframework.web.servlet.HandlerInterceptor;
+import org.springframework.web.servlet.ModelAndView;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.lang.reflect.Method;
+import java.time.LocalDateTime;
+import java.util.List;
+
+
+public class AuthenticationInterceptor implements HandlerInterceptor {
+    @Autowired
+    UserService userService;
+
+    @Override
+    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
+        String access_token = TokenUtil.getRequestToken(httpServletRequest);
+        // 如果不是映射到方法直接通过
+        if(!(object instanceof HandlerMethod)){
+            return true;
+        }
+        HandlerMethod handlerMethod=(HandlerMethod)object;
+        Method method=handlerMethod.getMethod();
+        //检查是否有passtoken注释,有则跳过认证
+        if (method.isAnnotationPresent(PassToken.class)) {
+            PassToken passToken = method.getAnnotation(PassToken.class);
+            if (passToken.required()) {
+                return true;
+            }
+        }
+        //检查有没有需要用户权限的注解
+        if (method.isAnnotationPresent(UserLoginToken.class)) {
+            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
+            if (userLoginToken.required()) {
+                // 执行认证
+                if (access_token == null) {
+                    throw new RuntimeException(JSONObject.toJSONString(ResultUtil.build(ResultStatusCode.SHIRO_ERROR)));
+                }
+                //1. 根据token,查询用户信息
+                List<Login> logins = userService.findByToken(access_token);
+                //2. 若用户不存在,
+                if (logins.isEmpty()) {
+                    throw new RuntimeException(JSONObject.toJSONString(ResultUtil.build(ResultStatusCode.LOGINED_IN2)));
+                }
+                //3. token失效
+                LocalDateTime tie = LocalDateTime.parse(logins.get(0).getAccess_token());
+                if (tie.isBefore(LocalDateTime.now())) {
+                    throw new RuntimeException(JSONObject.toJSONString(ResultUtil.build(ResultStatusCode.LOGINED_IN3)));
+                }
+                return true;
+            }
+        }
+        return true;
+    }
+
+    @Override
+    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
+
+    }
+    @Override
+    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
+
+    }
+}

+ 133 - 0
Base64.java

@@ -0,0 +1,133 @@
+package com.happy.Unitil_elc;
+
+import java.io.ByteArrayOutputStream;
+
+public class Base64 {
+
+    // map 6-bit int to char
+    private static final char[] chars64 = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a',
+                                            'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1',
+                                            '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };
+
+    // map char to 6-bit int
+    private static final int[]  ints64  = new int[128];
+    static {
+        for (int i = 0; i < 64; i++) {
+            ints64[chars64[i]] = i;
+        }
+    }
+
+    /**
+     * 转换byte数组成Base64 string
+     * 
+     * @param unencoded
+     * @return
+     */
+    public static final String encode(byte[] unencoded) {
+        // Take 24-bits from three octets, translate into four encoded chars.
+        // If necessary, pad with 0 bits on the right at the end
+        // Use = signs as padding at the end to ensure encodedLength % 4 == 0
+        if (unencoded == null || unencoded.length == 0) return null;
+
+        ByteArrayOutputStream out = new ByteArrayOutputStream((int) (unencoded.length * 1.37));
+        int byteCount = 0;
+        int carryOver = 0;
+
+        for (int i = 0; i < unencoded.length; i++) {
+            int bc = (byteCount % 3);
+            byte b = unencoded[i];
+            int lookup = 0;
+
+            // First byte use first six bits, save last two bits
+            if (bc == 0) {
+                lookup = (b >> 2) & 0x3F;
+                carryOver = b & 0x03; // last two bits
+                out.write(chars64[lookup]);
+            } else if (bc == 1) {
+                // Second byte use previous two bits and first four new bits,
+                // save last four bits
+                lookup = ((carryOver << 4) | ((b >> 4) & 0x0F));
+                carryOver = b & 0x0F; // last four bits
+                out.write(chars64[lookup]);
+            } else if (bc == 2) {
+                // Third byte use previous four bits and first two new bits,
+                // then use last six new bits
+                lookup = ((carryOver << 2) | ((b >> 6) & 0x03));
+                out.write(chars64[lookup]);
+
+                lookup = b & 0x3F; // last six bits
+                out.write(chars64[lookup]);
+                carryOver = 0;
+            }
+            byteCount++;
+        }
+
+        if (byteCount % 3 == 1) { // one leftover
+            int lookup = (carryOver << 4) & 0xF0;
+            out.write(chars64[lookup]);
+            out.write('=');
+            out.write('=');
+        } else if (byteCount % 3 == 2) { // two leftovers
+            int lookup = (carryOver << 2) & 0x3C;
+            out.write(chars64[lookup]);
+            out.write('=');
+        }
+        return out.toString();
+    }
+
+    /**
+     * Decode Base64 string back to byte array
+     * 
+     * @param encoded
+     * @return
+     */
+    public static final byte[] decode(String encoded) {
+        if (encoded == null || encoded.length() == 0) return null;
+
+        byte[] bytes = encoded.getBytes();
+
+        ByteArrayOutputStream out = new ByteArrayOutputStream((int) (bytes.length * 0.67));
+        int byteCount = 0;
+        int carryOver = 0;
+
+        DECODE_LOOP: for (int i = 0; i < bytes.length; i++) {
+            int ch = bytes[i];
+
+            // Read the next non-whitespace character
+            // if (Character.isWhitespace((char)ch))
+            // continue;
+
+            // The '=' sign is just padding; geffective end of stream
+            if (ch == '=') break DECODE_LOOP;
+
+            // Convert from raw form to 6-bit form
+            int newbits = ints64[ch];
+
+            int bc = (byteCount % 4);
+            if (bc == 0) {
+                // First char save all six bits, go for another
+                carryOver = newbits & 0x3F;
+            } else if (bc == 1) {
+                // second char use 6 previous bits and first 2 new bits
+                int data = ((carryOver << 2) + ((newbits >> 4) & 0x03));
+                out.write(data);
+                carryOver = newbits & 0x0F; // save 4 bits
+            } else if (bc == 2) {
+                // Third char use previous four bits and first four new bits,
+                // save last two bits
+                int data = ((carryOver << 4) + ((newbits >> 2) & 0x0F));
+                out.write(data);
+                carryOver = newbits & 0x03; // save 2 bits
+            } else if (bc == 3) {
+                // Fourth char use previous two bits and all six new bits
+                int data = ((carryOver << 6) + (newbits & 0x3F));
+                out.write(data);
+                carryOver = 0;
+            }
+            byteCount++;
+        }
+
+        return out.toByteArray();
+    }
+
+}

+ 230 - 0
Build.java

@@ -0,0 +1,230 @@
+package com.happy.action;
+
+import com.alibaba.fastjson.JSONObject;
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+import com.happy.Model.Build_elec;
+import com.happy.Model.Price;
+import com.happy.Until.ResUtil;
+import com.happy.Until.ResponseUtil;
+import com.happy.service.ConsumeService;
+import com.happy.service.ElecService;
+import com.happy.service.RechargeService;
+import com.happy.service.UserService;
+import com.opensymphony.xwork2.ActionSupport;
+import net.sf.json.JSONArray;
+import org.apache.struts2.ServletActionContext;
+import org.apache.struts2.interceptor.ServletRequestAware;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.RedisTemplate;
+import testExport.DataClient;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.math.BigDecimal;
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+public class Build extends ActionSupport implements ServletRequestAware {
+
+    private HttpServletRequest request;
+    public HttpServletResponse response;
+    public String roomSelect;
+
+
+    @Resource
+    public ElecService elecService;
+    @Resource
+    public UserService userService;
+    @Resource
+    public ConsumeService consumeService;
+    @Resource
+    public RechargeService rechargeService;
+    @Autowired
+    public RedisTemplate redisTemplate;
+
+    public String getRoomSelect() {
+        return roomSelect;
+    }
+
+    public void setRoomSelect(String roomSelect) {
+        this.roomSelect = roomSelect;
+    }
+
+    public HttpServletRequest getRequest() {
+        return request;
+    }
+
+    public void setRequest(HttpServletRequest request) {
+        this.request = request;
+    }
+
+    public void setServletRequest(HttpServletRequest request) {
+        this.request = request;
+    }
+
+    public HttpServletResponse getResponse() {
+        return response;
+    }
+
+    public void setResponse(HttpServletResponse response) {
+        this.response = response;
+    }
+
+
+    // 楼栋信息接口
+    public String bd_elec() throws Exception {
+        ArrayList<JSONObject> aj_school = new ArrayList<>();
+        List<Build_elec> schools = elecService.querySchool();
+        for (int i=0; i<schools.size(); i++) {
+            JSONObject resultJson1 = new JSONObject();
+            resultJson1.put("school", schools.get(i).getSchool());
+            List<Build_elec> builds = elecService.queryBuild(schools.get(i).getSchool());
+            ArrayList<JSONObject> aj_build = new ArrayList();
+            //resultJson1.put("builds", aj2);
+            for (int j=0; j<builds.size(); j++){
+                JSONObject resultJson2 = new JSONObject();
+                resultJson2.put("building", builds.get(j).getBuild());
+                List<Build_elec> floors = elecService.queryFloors(
+                        schools.get(i).getSchool(), builds.get(j).getBuild());
+                ArrayList<JSONObject> aj_floor = new ArrayList();
+                for (int k=0; k<floors.size(); k++){
+                    JSONObject resultJson3 = new JSONObject();
+                    resultJson3.put("floor", floors.get(k).getFloors());
+                    List<Build_elec> dom = elecService.queryDom(
+                            schools.get(i).getSchool(), builds.get(j).getBuild(), floors.get(k).getFloors());
+                    ArrayList adom = new ArrayList();
+                    for (int m=0; m<dom.size(); m++){
+                        adom.add(dom.get(m).getDom());
+                    }
+                    resultJson3.put("rooms", adom);
+                    aj_floor.add(resultJson3);
+                }
+                resultJson2.put("floors", aj_floor);
+                aj_build.add(resultJson2);
+            }
+            resultJson1.put("builds", aj_build);
+            aj_school.add(resultJson1);
+        }
+        String resultJson = JSONArray.fromObject(aj_school).toString();
+        try {
+            redisTemplate.delete("build");
+        }catch (Exception e){
+            System.out.println("build已清");
+        }
+        redisTemplate.opsForValue().set("build", resultJson);
+        ResUtil.write("绑定成功", ServletActionContext.getResponse());
+        return null;
+    }
+
+    // 返回楼栋信息
+    public String elec() throws Exception {
+        JSONObject resultJson = new JSONObject();
+        try {
+            String data = (String) redisTemplate.opsForValue().get("build");
+            resultJson.put("mess", "返回成功");
+            resultJson.put("data", data);
+        }catch (Exception e){
+            resultJson.put("mess", "获取数据异常");
+        }
+        ResUtil.write(resultJson, ServletActionContext.getResponse());
+        return null;
+    }
+
+    // 查询剩余电量
+    public String overElec() throws Exception {
+        JSONObject resultJson = new JSONObject();
+        if (roomSelect==null){
+            resultJson.put("mess", "请选择房间号!");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        String school = roomSelect.substring(0, 5);
+        String room = roomSelect.substring(5);
+        List<Build_elec> spl = elecService.queryUser_id(school, room);
+        if (spl == null){
+            resultJson.put("mess", "未查询到户号!");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        String user_id = spl.get(0).getUser_id().replace("\n","").replace("\r","");
+        DataClient.getToken();
+        JSONObject jb = DataClient.getAccountInfo(user_id);
+        if (jb == null){
+            resultJson.put("mess", "未查询到户号!");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        Object data = jb.get("data");
+        Gson gson=new Gson();
+        HashMap<String, String> userMoney = gson.fromJson(data.toString(), new TypeToken<HashMap<String, String>>(){}.getType());
+        double elcMoney = Double.parseDouble(userMoney.get("usablemoney"));
+        Double amount = 0.00;
+        List<Price> elcPrice = consumeService.water_price("电费");
+        amount = elcMoney / elcPrice.get(0).getPrice() ;
+        System.out.println(amount);
+        JSONObject j2 = new JSONObject();
+        j2.put("mess", "0");
+        j2.put("amount", amount);
+        ResUtil.write(j2, ServletActionContext.getResponse());
+        return null;
+    }
+
+    // 查询每个月电费
+    public String getMonthBill() throws Exception {
+        JSONObject resultJson = new JSONObject();
+        if (roomSelect==null){
+            resultJson.put("mess", "请选择房间号!");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        String school = roomSelect.substring(0, 5);
+        String room = roomSelect.substring(5);
+        List<Build_elec> spl = elecService.queryUser_id(school, room);
+        if (spl == null){
+            resultJson.put("mess", "未查询到户号!");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        String user_id = spl.get(0).getUser_id();
+        DataClient.getToken();
+        List<String> dateList = new ArrayList<>();
+        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
+        for (int i=0; i>-12; i--){
+            Calendar calendar = Calendar.getInstance();
+            calendar.add(Calendar.MONTH,i);
+            dateList.add(simpleDateFormat.format(calendar.getTime()));
+        }
+        String da = JSONArray.fromObject(dateList).toString();
+        JSONObject json = DataClient.getMonthBill(user_id, da);
+        Gson gson=new Gson();
+        Object data=null;
+        try {
+            data = json.get("data");
+        }catch (Exception e){
+            resultJson.put("mess", "未查询到数据");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        List<HashMap<String, String>> user_elc = gson.fromJson(data.toString(), new TypeToken<List<HashMap<String, String>>>(){}.getType());
+        if (user_elc==null){
+            resultJson.put("mess", "未查询到数据");
+            return null;
+        }
+        ArrayList<String> use_elc = new ArrayList<>();
+        ArrayList<String> date_time = new ArrayList<>();
+        for (int i=0; i<user_elc.size(); i++){
+            use_elc.add(user_elc.get(i).get("zongPower"));
+            date_time.add(user_elc.get(i).get("dataTime"));
+        }
+
+        resultJson.put("use_elc", use_elc);
+        resultJson.put("date_time", date_time);
+        resultJson.put("mess", "0");
+        ResUtil.write(resultJson, ServletActionContext.getResponse());
+        return null;
+    }
+
+
+}

+ 77 - 0
Build_elec.java

@@ -0,0 +1,77 @@
+package com.happy.Model;
+
+public class Build_elec {
+
+    public int id;
+    public String school;
+    public String build;
+    public String floors;
+    public String dom;
+    public String user_id;
+    public String pointid;
+    public double use_size;
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getSchool() {
+        return school;
+    }
+
+    public void setSchool(String school) {
+        this.school = school;
+    }
+
+    public String getBuild() {
+        return build;
+    }
+
+    public void setBuild(String build) {
+        this.build = build;
+    }
+
+    public String getFloors() {
+        return floors;
+    }
+
+    public void setFloors(String floors) {
+        this.floors = floors;
+    }
+
+    public String getDom() {
+        return dom;
+    }
+
+    public void setDom(String dom) {
+        this.dom = dom;
+    }
+
+    public String getUser_id() {
+        return user_id;
+    }
+
+    public void setUser_id(String user_id) {
+        this.user_id = user_id;
+    }
+
+    public String getPointid() {
+        return pointid;
+    }
+
+    public void setPointid(String pointid) {
+        this.pointid = pointid;
+    }
+
+    public double getUse_size() {
+        return use_size;
+    }
+
+    public void setUse_size(double use_size) {
+        this.use_size = use_size;
+    }
+}

+ 60 - 0
Build_water.java

@@ -0,0 +1,60 @@
+package com.happy.Model;
+
+public class Build_water {
+
+    public int id;
+    public String school;
+    public String build;
+    public String floors;
+    public String dom;
+    public String user_id;
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getSchool() {
+        return school;
+    }
+
+    public void setSchool(String school) {
+        this.school = school;
+    }
+
+    public String getBuild() {
+        return build;
+    }
+
+    public void setBuild(String build) {
+        this.build = build;
+    }
+
+    public String getFloors() {
+        return floors;
+    }
+
+    public void setFloors(String floors) {
+        this.floors = floors;
+    }
+
+    public String getDom() {
+        return dom;
+    }
+
+    public void setDom(String dom) {
+        this.dom = dom;
+    }
+
+    public String getUser_id() {
+        return user_id;
+    }
+
+    public void setUser_id(String user_id) {
+        this.user_id = user_id;
+    }
+
+}

+ 31 - 0
CharacterEncodingFilter.java

@@ -0,0 +1,31 @@
+//
+// Source code recreated from a .class file by IntelliJ IDEA
+// (powered by Fernflower decompiler)
+//
+
+package com.happy.filter;
+
+import java.io.IOException;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+public class CharacterEncodingFilter implements Filter {
+	public CharacterEncodingFilter() {
+	}
+
+	public void destroy() {
+	}
+
+	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+		request.setCharacterEncoding("utf-8");
+		response.setCharacterEncoding("utf-8");
+		chain.doFilter(request, response);
+	}
+
+	public void init(FilterConfig arg0) throws ServletException {
+	}
+}

+ 21 - 0
Clien_test.java

@@ -0,0 +1,21 @@
+package testExport;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.happy.Model.QueryUrlEnum;
+import com.happy.Unitil_elc.CodeUtil;
+import com.happy.Unitil_elc.HttpClientHelper;
+import com.happy.Unitil_elc.JsonUtil;
+import com.happy.Unitil_elc.StringUtil;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+public class Clien_test {
+    public static void main(String[] args) {
+        DataClient.getToken();
+        DataClient.getUserAccountInfo();
+    }
+}

+ 198 - 0
CodeUtil.java

@@ -0,0 +1,198 @@
+package com.happy.Unitil_elc;
+
+import javax.crypto.Cipher;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+public class CodeUtil {
+
+
+    /**
+     * 解密
+     * @param src       源数据
+     * @param secret    秘钥
+     * @param iv        初始化向量
+     * @return          String
+     */
+    public static String dataDecode(String src, String secret, String iv){
+        try {
+            // 判断Key是否正确
+            if (secret == null) {
+                System.out.print("Key为空null");
+                return null;
+            }
+            // 判断Key是否为16位
+            if (secret.length() != 16) {
+                System.out.print("Key长度不是16位");
+                return null;
+            }
+            byte[] raw = secret.getBytes(StandardCharsets.US_ASCII);
+            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
+            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+            IvParameterSpec ips  = new IvParameterSpec(iv.getBytes());
+            cipher.init(Cipher.DECRYPT_MODE, skeySpec, ips);
+            // byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密
+            byte[] encrypted1 = Base64.decode(src);
+            try {
+                byte[] original = cipher.doFinal(encrypted1);
+                return new String(original, StandardCharsets.UTF_8);
+            } catch (Exception e) {
+                System.out.println(e.toString());
+                return null;
+            }
+        } catch (Exception ex) {
+            System.out.println(ex.toString());
+            return null;
+        }
+    }
+
+    /**
+     *  加密
+     * @param src       源数据
+     * @param secret    秘钥
+     * @param iv        初始化向量
+     * @return          String
+     */
+    public static String dataEncode(String src, String secret, String iv) throws Exception {
+        if (secret == null) {
+            System.out.print("Key为空null");
+            return null;
+        }
+        // 判断Key是否为16位
+        if (secret.length() != 16) {
+            System.out.print("Key长度不是16位");
+            return null;
+        }
+        byte[] raw = secret.getBytes(StandardCharsets.UTF_8);
+        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
+        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// "算法/模式/补码方式"
+        IvParameterSpec ips = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
+        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ips);
+        byte[] encrypted = cipher.doFinal(src.getBytes(StandardCharsets.UTF_8));
+        // return new BASE64Encoder().encode(encrypted);// 此处使用BASE64做转码功能,同时能起到2次加密的作用。
+        return Base64.encode(encrypted);
+    }
+
+    /**
+     * 获取签名
+     * @param src       源数据
+     * @param signKey   签名秘钥
+     * @return          String
+     */
+    public static String getSign(String src,String signKey){
+        String result = "";
+        try {
+            byte[] keyByte = signKey.getBytes(StandardCharsets.UTF_8);
+            byte[] dataByte = src.getBytes(StandardCharsets.UTF_8);
+            byte[] hmacMd5Byte = getHmacMd5Bytes(keyByte, dataByte);
+            StringBuilder md5Str = new StringBuilder();
+            for (byte b : hmacMd5Byte) {
+                if (Integer.toHexString(0xFF & b).length() == 1) md5Str.append("0").append(Integer.toHexString(0xFF & b));
+                else md5Str.append(Integer.toHexString(0xFF & b));
+            }
+            result = md5Str.toString().toUpperCase();
+
+        } catch (Exception ignored) {
+        }
+        return result;
+
+    }
+
+
+    /**
+     * 将待加密数据data,通过密钥key,使用hmac-md5算法进行加密,然后返回加密结果。 参照rfc2104 HMAC算法介绍实现。
+     *
+     * @author sc
+     * @param key 密钥
+     * @param data 待加密数据
+     * @return 加密结果
+     */
+    private static byte[] getHmacMd5Bytes(byte[] key, byte[] data) throws NoSuchAlgorithmException {
+        /*
+         * HmacMd5 calculation formula: H(K XOR opad, H(K XOR ipad, text)) HmacMd5 计算公式:H(K XOR opad, H(K XOR ipad,
+         * text)) H代表hash算法,本类中使用MD5算法,K代表密钥,text代表要加密的数据 ipad为0x36,opad为0x5C。
+         */
+        int length = 64;
+        byte[] ipad = new byte[length];
+        byte[] opad = new byte[length];
+        for (int i = 0; i < 64; i++) {
+            ipad[i] = 0x36;
+            opad[i] = 0x5C;
+        }
+        byte[] actualKey = key; // Actual key.
+        byte[] keyArr = new byte[length]; // Key bytes of 64 bytes length
+        /*
+         * If key's length is longer than 64,then use hash to digest it and use the result as actual key.
+         * 如果密钥长度,大于64字节,就使用哈希算法,计算其摘要,作为真正的密钥。
+         */
+        if (key.length > length) {
+            actualKey = md5(key);
+        }
+        System.arraycopy(actualKey, 0, keyArr, 0, actualKey.length);
+        /*
+         * append zeros to K 如果密钥长度不足64字节,就使用0x00补齐到64字节。
+         */
+        if (actualKey.length < length) {
+            for (int i = actualKey.length; i < keyArr.length; i++)
+                keyArr[i] = 0x00;
+        }
+
+        /*
+         * calc K XOR ipad 使用密钥和ipad进行异或运算。
+         */
+        byte[] kIpadXorResult = new byte[length];
+        for (int i = 0; i < length; i++) {
+            kIpadXorResult[i] = (byte) (keyArr[i] ^ ipad[i]);
+        }
+
+        /*
+         * append "text" to the end of "K XOR ipad" 将待加密数据追加到K XOR ipad计算结果后面。
+         */
+        byte[] firstAppendResult = new byte[kIpadXorResult.length + data.length];
+        System.arraycopy(kIpadXorResult, 0, firstAppendResult, 0, kIpadXorResult.length);
+        System.arraycopy(data, 0, firstAppendResult, keyArr.length, data.length);
+
+        /*
+         * calc H(K XOR ipad, text) 使用哈希算法计算上面结果的摘要。
+         */
+        byte[] firstHashResult = md5(firstAppendResult);
+
+        /*
+         * calc K XOR opad 使用密钥和opad进行异或运算。
+         */
+        byte[] kOpadXorResult = new byte[length];
+        for (int i = 0; i < length; i++) {
+            kOpadXorResult[i] = (byte) (keyArr[i] ^ opad[i]);
+        }
+
+        /*
+         * append "H(K XOR ipad, text)" to the end of "K XOR opad" 将H(K XOR ipad, text)结果追加到K XOR opad结果后面
+         */
+        byte[] secondAppendResult = new byte[kOpadXorResult.length + firstHashResult.length];
+        System.arraycopy(kOpadXorResult, 0, secondAppendResult, 0, kOpadXorResult.length);
+        System.arraycopy(firstHashResult, 0, secondAppendResult, keyArr.length, firstHashResult.length);
+
+        /*
+         * H(K XOR opad, H(K XOR ipad, text)) 对上面的数据进行哈希运算。
+         */
+        return md5(secondAppendResult);
+    }
+
+
+    /**
+     * 计算参数的md5信息
+     *
+     * @param str 待处理的字节数组
+     * @return md5摘要信息
+     */
+    private static byte[] md5(byte[] str) throws NoSuchAlgorithmException {
+        MessageDigest md = MessageDigest.getInstance("MD5");
+        md.update(str);
+        return md.digest();
+    }
+
+
+}

+ 50 - 0
Config.java

@@ -0,0 +1,50 @@
+package com.happy.Model;
+
+public class Config {
+
+    public int id;
+    public String name;
+    public int value;
+    public String text;
+    public double amount;
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public int getValue() {
+        return value;
+    }
+
+    public void setValue(int value) {
+        this.value = value;
+    }
+
+    public String getText() {
+        return text;
+    }
+
+    public void setText(String text) {
+        this.text = text;
+    }
+
+    public double getAmount() {
+        return amount;
+    }
+
+    public void setAmount(double amount) {
+        this.amount = amount;
+    }
+}

+ 10 - 0
ConfigDao.java

@@ -0,0 +1,10 @@
+package com.happy.dao;
+
+import com.happy.Model.Config;
+
+import java.util.List;
+
+public interface ConfigDao {
+
+    public List<Config> query(String name);
+}

+ 39 - 0
ConfigDaoImpl.java

@@ -0,0 +1,39 @@
+package com.happy.dao.impl;
+
+import com.happy.Model.Config;
+import com.happy.Model.Consume;
+import com.happy.dao.ConfigDao;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.jdbc.core.BeanPropertyRowMapper;
+import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
+import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
+import org.springframework.stereotype.Repository;
+
+import java.util.List;
+
+@Repository("ConfigDao")
+public class ConfigDaoImpl implements ConfigDao {
+
+    @Autowired
+    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
+
+    public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
+        return namedParameterJdbcTemplate;
+    }
+
+    public void setNamedParameterJdbcTemplate(
+            NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
+        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
+    }
+
+    public List<Config> query(String name){
+        String sql="select * from config where name=:name";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("name", name);
+        List<Config> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Config>(Config.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+}

+ 10 - 0
ConfigService.java

@@ -0,0 +1,10 @@
+package com.happy.service;
+
+import com.happy.Model.Config;
+
+import java.util.List;
+
+public interface ConfigService {
+
+    public List<Config> query(String name);
+}

+ 29 - 0
ConfigServiceImpl.java

@@ -0,0 +1,29 @@
+package com.happy.service.impl;
+
+import com.happy.Model.Config;
+import com.happy.dao.ConfigDao;
+import com.happy.dao.ConsumeDao;
+import com.happy.service.ConfigService;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+@Service("ConfigService")
+public class ConfigServiceImpl implements ConfigService {
+
+    @Resource
+    public ConfigDao configDao;
+
+    public ConfigDao getConfigDao() {
+        return configDao;
+    }
+
+    public void setConfigDao(ConfigDao configDao) {
+        this.configDao = configDao;
+    }
+
+    public List<Config> query(String name){
+        return configDao.query(name);
+    }
+}

+ 98 - 0
ConstDefault.java

@@ -0,0 +1,98 @@
+package com.happy.constant;
+
+import org.apache.http.client.HttpClient;
+
+import java.text.SimpleDateFormat;
+
+/**
+ * lockcslock
+ *
+ * @author yp
+ */
+public final class ConstDefault {
+
+    public static final String DATETIMES_FORMAT_STRING = "yyyy-MM-dd HH:mm:ss";
+    public static final String DATE_FORMAT_STRING = "yyyy-MM-dd";
+    public static final String TIMES_FORMAT_STRING = "HH:mm:ss";
+
+    public static final SimpleDateFormat DATETIMES_FORMAT = new SimpleDateFormat(DATETIMES_FORMAT_STRING);
+    public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(DATE_FORMAT_STRING);
+    public static final SimpleDateFormat TIMES_FORMAT = new SimpleDateFormat(TIMES_FORMAT_STRING);
+
+    public final static class USERROLE {
+        public final static int NORMMAL = 4;
+        public final static int SYSTEMADMIN = 1;
+        public final static int DEVICEADMIN = 2;
+    }
+
+    public final static class THIRDTYPE {
+
+        public final static int WEIXINPUBLIC = 1;
+        public final static int WEIXIN_MINI = 2;
+        public final static int WEIXIN_OPEN = 3;
+
+    }
+
+    public final static int ANONYMOUSID = -1;
+    public final static int DEFAULTORG = 1;
+    public final static int DEFAULTROLEPERMISSON = 0;
+    public final static int SOUND_KEY = 1;
+
+    //密码得前缀字符串
+    public static String FTSTR = "PARTYDUES";
+    //密码得后缀字符串
+    public static String BGSTR = "LYKJ";
+
+    //微信登录的token
+    public static String WXID = "wx";
+
+    public static String WXPASSWORD = "partydues";
+
+    public enum SignType {
+        MD5, HMACSHA256
+    }
+
+    public static final String DOMAIN_API = "api.mch.weixin.qq.com";
+    public static final String DOMAIN_API2 = "api2.mch.weixin.qq.com";
+    public static final String DOMAIN_APIHK = "apihk.mch.weixin.qq.com";
+    public static final String DOMAIN_APIUS = "apius.mch.weixin.qq.com";
+
+    public static final String FAIL     = "FAIL";
+    public static final String SUCCESS  = "SUCCESS";
+    public static final String HMACSHA256 = "HMAC-SHA256";
+    public static final String MD5 = "MD5";
+
+    public static final String FIELD_SIGN = "sign";
+    public static final String FIELD_SIGN_TYPE = "sign_type";
+
+    public static final String WXPAYSDK_VERSION = "WXPaySDK/3.0.9";
+    public static final String USER_AGENT = WXPAYSDK_VERSION +
+            " (" + System.getProperty("os.arch") + " " + System.getProperty("os.name") + " " + System.getProperty("os.version") +
+            ") Java/" + System.getProperty("java.version") + " HttpClient/" + HttpClient.class.getPackage().getImplementationVersion();
+
+    public static final String MICROPAY_URL_SUFFIX     = "/pay/micropay";
+    public static final String UNIFIEDORDER_URL_SUFFIX = "/pay/unifiedorder";
+    public static final String ORDERQUERY_URL_SUFFIX   = "/pay/orderquery";
+    public static final String REVERSE_URL_SUFFIX      = "/secapi/pay/reverse";
+    public static final String CLOSEORDER_URL_SUFFIX   = "/pay/closeorder";
+    public static final String REFUND_URL_SUFFIX       = "/secapi/pay/refund";
+    public static final String REFUNDQUERY_URL_SUFFIX  = "/pay/refundquery";
+    public static final String DOWNLOADBILL_URL_SUFFIX = "/pay/downloadbill";
+    public static final String REPORT_URL_SUFFIX       = "/payitil/report";
+    public static final String SHORTURL_URL_SUFFIX     = "/tools/shorturl";
+    public static final String AUTHCODETOOPENID_URL_SUFFIX = "/tools/authcodetoopenid";
+
+    // sandbox
+    public static final String SANDBOX_MICROPAY_URL_SUFFIX     = "/sandboxnew/pay/micropay";
+    public static final String SANDBOX_UNIFIEDORDER_URL_SUFFIX = "/sandboxnew/pay/unifiedorder";
+    public static final String SANDBOX_ORDERQUERY_URL_SUFFIX   = "/sandboxnew/pay/orderquery";
+    public static final String SANDBOX_REVERSE_URL_SUFFIX      = "/sandboxnew/secapi/pay/reverse";
+    public static final String SANDBOX_CLOSEORDER_URL_SUFFIX   = "/sandboxnew/pay/closeorder";
+    public static final String SANDBOX_REFUND_URL_SUFFIX       = "/sandboxnew/secapi/pay/refund";
+    public static final String SANDBOX_REFUNDQUERY_URL_SUFFIX  = "/sandboxnew/pay/refundquery";
+    public static final String SANDBOX_DOWNLOADBILL_URL_SUFFIX = "/sandboxnew/pay/downloadbill";
+    public static final String SANDBOX_REPORT_URL_SUFFIX       = "/sandboxnew/payitil/report";
+    public static final String SANDBOX_SHORTURL_URL_SUFFIX     = "/sandboxnew/tools/shorturl";
+    public static final String SANDBOX_AUTHCODETOOPENID_URL_SUFFIX = "/sandboxnew/tools/authcodetoopenid";
+
+}

+ 169 - 0
Consume.java

@@ -0,0 +1,169 @@
+package com.happy.Model;
+
+import java.math.BigDecimal;
+
+public class Consume {
+
+    public Integer id;
+    public String card_number;
+    public String stu_number;
+    public String user_name;
+    public String order_no;
+    public String pay_time;
+    public String begin_time;
+    public String end_time;
+    public double use_amount;
+    public String merchant_name;
+    public String start_code;
+    public String device_code;
+    public Integer type;
+    public int state;
+    public double use_size;
+    public double rate;
+    public String build;
+    public String dom;
+
+    public String getStu_number() {
+        return stu_number;
+    }
+
+    public void setStu_number(String stu_number) {
+        this.stu_number = stu_number;
+    }
+
+    public double getUse_amount() {
+        return use_amount;
+    }
+
+    public void setUse_amount(double use_amount) {
+        this.use_amount = use_amount;
+    }
+
+    public int getState() {
+        return state;
+    }
+
+    public void setState(int state) {
+        this.state = state;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public String getCard_number() {
+        return card_number;
+    }
+
+    public void setCard_number(String card_number) {
+        this.card_number = card_number;
+    }
+
+    public String getUser_name() {
+        return user_name;
+    }
+
+    public void setUser_name(String user_name) {
+        this.user_name = user_name;
+    }
+
+    public String getOrder_no() {
+        return order_no;
+    }
+
+    public void setOrder_no(String order_no) {
+        this.order_no = order_no;
+    }
+
+    public String getPay_time() {
+        return pay_time;
+    }
+
+    public void setPay_time(String pay_time) {
+        this.pay_time = pay_time;
+    }
+
+    public String getBegin_time() {
+        return begin_time;
+    }
+
+    public void setBegin_time(String begin_time) {
+        this.begin_time = begin_time;
+    }
+
+    public String getEnd_time() {
+        return end_time;
+    }
+
+    public void setEnd_time(String end_time) {
+        this.end_time = end_time;
+    }
+
+    public double getUse_size() {
+        return use_size;
+    }
+
+    public void setUse_size(double use_size) {
+        this.use_size = use_size;
+    }
+
+    public String getMerchant_name() {
+        return merchant_name;
+    }
+
+    public void setMerchant_name(String merchant_name) {
+        this.merchant_name = merchant_name;
+    }
+
+    public String getStart_code() {
+        return start_code;
+    }
+
+    public void setStart_code(String start_code) {
+        this.start_code = start_code;
+    }
+
+    public String getDevice_code() {
+        return device_code;
+    }
+
+    public void setDevice_code(String device_code) {
+        this.device_code = device_code;
+    }
+
+    public Integer getType() {
+        return type;
+    }
+
+    public void setType(Integer type) {
+        this.type = type;
+    }
+
+    public double getRate() {
+        return rate;
+    }
+
+    public void setRate(double rate) {
+        this.rate = rate;
+    }
+
+    public String getBuild() {
+        return build;
+    }
+
+    public void setBuild(String build) {
+        this.build = build;
+    }
+
+    public String getDom() {
+        return dom;
+    }
+
+    public void setDom(String dom) {
+        this.dom = dom;
+    }
+}

+ 28 - 0
ConsumeDao.java

@@ -0,0 +1,28 @@
+package com.happy.dao;
+
+import com.happy.Model.Consume;
+import com.happy.Model.Price;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+public interface ConsumeDao {
+
+    public List<Consume> queryRecordByOrder(String order_no);
+
+    public List<Consume> queryRecordByCard(String card_number, String begin_time);
+
+    public List<Consume> queryRecordByStu(String stu_number, String begin_time);
+
+    public int insertComsume(Consume consume);
+
+    public int updateBalance(String stu_number, double balance);
+
+    public int updateConsume2(String order_no, String pay_time, double use_amount, double use_size, int state);
+
+    public int updateConsume(String order_no, String pay_time, BigDecimal use_amount, BigDecimal use_size, int state);
+
+    public int updateConsumeStu(String stu_number, String user_name, String order_no);
+
+    public List<Price> water_price(String name);
+}

+ 162 - 0
ConsumeDaoImpl.java

@@ -0,0 +1,162 @@
+package com.happy.dao.impl;
+
+import com.happy.Model.Consume;
+import com.happy.Model.Price;
+import com.happy.dao.ConsumeDao;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.jdbc.core.BeanPropertyRowMapper;
+import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
+import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
+import org.springframework.stereotype.Repository;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+@Repository("ConsumeDao")
+public class ConsumeDaoImpl implements ConsumeDao {
+
+    @Autowired
+    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
+
+    public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
+        return namedParameterJdbcTemplate;
+    }
+
+    public void setNamedParameterJdbcTemplate(
+            NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
+        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
+    }
+
+    public List<Consume> queryRecordByOrder(String order_no){
+        String sql="select * from consume where order_no=:order_no";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("order_no", order_no);
+        List<Consume> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Consume>(Consume.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public List<Consume> queryRecordByCard(String card_number, String begin_time){
+        String sql="select * from consume where card_number=:card_number and use_amount>0 and begin_time like '"+ begin_time +"%' order by id desc";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("card_number", card_number);
+        List<Consume> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Consume>(Consume.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public List<Consume> queryRecordByStu(String stu_number, String begin_time){
+        String sql="select * from consume where stu_number=:stu_number and use_amount>0 and begin_time like '"+ begin_time +"%' order by id desc";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("stu_number", stu_number);
+        List<Consume> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Consume>(Consume.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public int insertComsume(Consume consume){
+        String sql = "insert into consume(stu_number, user_name, order_no, begin_time, start_code, device_code, use_amount, use_size, rate) values(:stu_number, :user_name, :order_no, :begin_time, :start_code, :device_code, :use_amount, :use_size, :rate)";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("stu_number", consume.getStu_number());
+        sps.addValue("user_name", consume.getUser_name());
+        sps.addValue("order_no", consume.getOrder_no());
+        sps.addValue("begin_time", consume.getBegin_time());
+        sps.addValue("start_code", consume.getStart_code());
+        sps.addValue("device_code", consume.getDevice_code());
+        sps.addValue("use_amount", consume.getUse_amount());
+        sps.addValue("use_size", consume.getUse_size());
+        sps.addValue("rate", consume.getRate());
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    public int updateBalance(String stu_number, double balance){
+        String sql = "update users set balance=:balance where stu_number=:stu_number";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("stu_number", stu_number);
+        sps.addValue("balance", balance);
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    public int updateConsume(String order_no, String pay_time, BigDecimal use_amount, BigDecimal use_size, int state){
+        String sql = "update consume set pay_time=:pay_time, use_amount=:use_amount, use_size=:use_size, state=:state where order_no=:order_no";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("pay_time", pay_time);
+        sps.addValue("use_amount", use_amount);
+        sps.addValue("state", state);
+        sps.addValue("order_no", order_no);
+        sps.addValue("use_size", use_size);
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    public int updateConsumeStu(String stu_number, String user_name, String order_no){
+        String sql = "update consume set stu_number=:stu_number, user_name=:user_name, order_no=:order_no where order_no=:order_no";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("stu_number", stu_number);
+        sps.addValue("user_name", user_name);
+        sps.addValue("order_no", order_no);
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    public int updateConsume2(String order_no, String pay_time, double use_amount, double use_size, int state){
+        String sql = "update consume set pay_time=:pay_time, use_amount=:use_amount, use_size=:use_size, state=:state where order_no=:order_no";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("pay_time", pay_time);
+        sps.addValue("use_amount", use_amount);
+        sps.addValue("state", state);
+        sps.addValue("order_no", order_no);
+        sps.addValue("use_size", use_size);
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    public List<Price> water_price(String name){
+        String sql = "select * from price where name=:name and state=1 and time in (select MAX(time) from `price` where name=:name and state=1)";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("name", name);
+        List<Price> list = namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Price>(Price.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+}

+ 28 - 0
ConsumeService.java

@@ -0,0 +1,28 @@
+package com.happy.service;
+
+import com.happy.Model.Consume;
+import com.happy.Model.Price;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+public interface ConsumeService {
+
+    public List<Consume> queryRecordByOrder(String order_no);
+
+    public List<Consume> queryRecordByCard(String card_number, String begin_time);
+
+    public List<Consume> queryRecordByStu(String stu_number, String begin_time);
+
+    public int insertComsume(Consume consume);
+
+    public int updateBalance(String stu_number, double balance);
+
+    public int updateConsume(String order_no, String pay_time, BigDecimal use_amount, BigDecimal use_size, int state);
+
+    public int updateConsumeStu(String stu_number, String user_name, String order_no);
+
+    public int updateConsume2(String order_no, String pay_time, double use_amount, double use_size, int state);
+
+    public List<Price> water_price(String name);
+}

+ 63 - 0
ConsumeServiceImpl.java

@@ -0,0 +1,63 @@
+package com.happy.service.impl;
+
+
+import com.happy.Model.Consume;
+import com.happy.Model.Price;
+import com.happy.dao.ConsumeDao;
+import com.happy.service.ConsumeService;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.math.BigDecimal;
+import java.util.List;
+
+@Service("ConsumeService")
+public class ConsumeServiceImpl implements ConsumeService {
+
+    @Resource
+    public ConsumeDao consumeDao;
+
+    public ConsumeDao getConsumeDao() {
+        return consumeDao;
+    }
+
+    public void setConsumeDao(ConsumeDao consumeDao) {
+        this.consumeDao = consumeDao;
+    }
+
+    public List<Consume> queryRecordByOrder(String order_no){
+        return consumeDao.queryRecordByOrder(order_no);
+    }
+
+    public List<Consume> queryRecordByCard(String card_number, String begin_time){
+        return consumeDao.queryRecordByCard(card_number, begin_time);
+    }
+
+    public List<Consume> queryRecordByStu(String stu_number, String begin_time){
+        return consumeDao.queryRecordByStu(stu_number, begin_time);
+    }
+
+    public int insertComsume(Consume consume){
+        return consumeDao.insertComsume(consume);
+    }
+
+    public int updateBalance(String stu_number, double balance){
+        return consumeDao.updateBalance(stu_number, balance);
+    }
+
+    public int updateConsume(String order_no, String pay_time, BigDecimal use_amount, BigDecimal use_size, int state){
+        return consumeDao.updateConsume(order_no, pay_time, use_amount, use_size, state);
+    }
+
+    public int updateConsumeStu(String stu_number, String user_name, String order_no){
+        return consumeDao.updateConsumeStu(stu_number, user_name, order_no);
+    }
+
+    public int updateConsume2(String order_no, String pay_time, double use_amount, double use_size, int state){
+        return consumeDao.updateConsume2(order_no, pay_time, use_amount, use_size, state);
+    }
+
+    public List<Price> water_price(String name){
+        return consumeDao.water_price(name);
+    }
+}

+ 65 - 0
CreateSign1.java

@@ -0,0 +1,65 @@
+package com.happy.Until;
+
+import com.alibaba.fastjson.JSONObject;
+
+import java.io.UnsupportedEncodingException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+public class CreateSign1 {
+    private static final char hexDigits[] = { '0', '1', '2', '3', '4', '5',
+            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
+
+    public static String MD5(String s) {
+        return MD5(s,"utf-8");
+    }
+
+    public static String MD5(String s, String charset) {
+        try{
+            MessageDigest messagedigest = MessageDigest.getInstance("MD5");
+            messagedigest.reset();
+            byte abyte0[] = messagedigest.digest(s.getBytes(charset));
+            return byteToString(abyte0);
+        } catch (NoSuchAlgorithmException e) {
+            e.printStackTrace();
+        } catch (UnsupportedEncodingException e) {
+            e.printStackTrace();
+        }
+        return "";
+    }
+
+    private static String byteToString(byte abyte0[]) {
+        int i = abyte0.length;
+        char ac[] = new char[i * 2];
+        int j = 0;
+        for (int k = 0; k < i; k++) {
+            byte byte0 = abyte0[k];
+            ac[j++] = hexDigits[byte0 >>> 4 & 0xf];
+            ac[j++] = hexDigits[byte0 & 0xf];
+        }
+        return new String(ac);
+    }
+
+    public static void main(String[] args) {
+        //密钥由艾停车提供,密钥和车场号一一对应
+        String ukey = "K1DIXZCLWNO0J0WV";
+
+        JSONObject data = new JSONObject(true);
+        data.put("uid","大门入口");
+        data.put("in_time",1611731098);
+        data.put("car_number","赣AE3434");
+        data.put("c_type","临时车");
+        data.put("in_channel_id","大门入口");
+        data.put("order_id","1902");
+        data.put("force_update",1);
+        data.put("empty_plot",879);
+        data.put("car_type","");
+        data.put("source","ist");
+        data.put("pic_addr","http://ist-falcon.oss-cn-shenzhen.aliyuncs.com/order-images/31809/in/1902.jpg?Expires=1611817499&OSSAccessKeyId=LTAIQQrl6GICP0QX&Signature=FnKZNrQ5nkdJlhgVTYp4v7Q3ejY%3D");
+
+        // 生成带签名的字符串并使用MD5生成签名,然后转大写
+        String sign = data.toJSONString()+"key="+ukey;
+        sign = MD5(sign).toUpperCase();
+        System.out.println(sign);//242441AAC1911DB6E47A942A2B6477D5
+    }
+}

+ 250 - 0
DBtoExcel.java

@@ -0,0 +1,250 @@
+package com.happy.Until;
+
+import jxl.Workbook;
+import jxl.write.Label;
+import jxl.write.WritableSheet;
+import jxl.write.WritableWorkbook;
+import jxl.write.WriteException;
+import jxl.write.biff.RowsExceededException;
+
+import java.io.File;
+import java.sql.ResultSet;
+import java.util.ArrayList;
+import java.util.Vector;
+
+public class DBtoExcel {
+	/**
+	 * 导出Excel表
+	 * 
+	 * @param rs
+	 *            数据库结果集
+	 * @param filePath
+	 *            要保存的路径,文件名为 fileName.xls
+	 * @param sheetName
+	 *            工作簿名称 工作簿名称,本方法目前只支持导出一个Excel工作簿
+	 * @param columnName
+	 *            列名,类型为Vector
+	 */
+	public void WriteExcel(ResultSet rs, String filePath, String sheetName,
+			Vector columnName) {
+		WritableWorkbook workbook = null;
+		WritableSheet sheet = null;
+
+		int rowNum = 1; // 从第2行开始写入
+		try {
+			workbook = Workbook.createWorkbook(new File(filePath)); // 创建Excel文件
+			sheet = workbook.createSheet(sheetName, 0); // 创建名为 sheetName 的工作簿
+
+			this.writeCol(sheet, columnName, 0); // 首先将列名写入第一行
+
+			// 将结果集写入
+			while (rs.next()) {
+				Vector col = new Vector(); // 用以保存一行数据
+
+				for (int i = 1; i <= columnName.size(); i++) { // 将一行内容保存在col中
+					col.add(rs.getString(i));
+				}
+				// 写入Excel
+				this.writeCol(sheet, col, rowNum++);
+			}
+
+		} catch (Exception e) {
+			e.printStackTrace();
+		} finally {
+			try {
+				// 关闭
+				workbook.write();
+				workbook.close();
+				rs.close();
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+		}
+	}
+
+	public void WriteExcel2(ResultSet rs, String filePath, String sheetName,
+						   Vector columnName, String time1, String time2) {
+		WritableWorkbook workbook = null;
+		WritableSheet sheet = null;
+
+		int rowNum = 2; // 从第一行开始写入
+		try {
+			workbook = Workbook.createWorkbook(new File(filePath)); // 创建Excel文件
+			sheet = workbook.createSheet(sheetName, 0); // 创建名为 sheetName 的工作簿
+
+			this.writeCol(sheet, columnName, 1); // 首先将列名写入
+
+			// 写入时间
+			Vector col2 = new Vector(); // 用以保存一行数据
+			col2.add("统计时间-:"+time1+"到"+time2);
+			this.writeCol(sheet, col2, 0);
+			// 将结果集写入
+			while (rs.next()) {
+				Vector col = new Vector(); // 用以保存一行数据
+
+				for (int i = 1; i <= columnName.size(); i++) { // 将一行内容保存在col中
+					col.add(rs.getString(i));
+				}
+				// 写入Excel
+				this.writeCol2(sheet, col, rowNum++);
+			}
+
+		} catch (Exception e) {
+			e.printStackTrace();
+		} finally {
+			try {
+				// 关闭
+				workbook.write();
+				workbook.close();
+				rs.close();
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+		}
+	}
+
+	public void WriteExcel4(ArrayList<ArrayList> aa, String filePath, String sheetName,
+							Vector columnName, String time1, String time2) {
+		WritableWorkbook workbook = null;
+		WritableSheet sheet = null;
+
+		int rowNum = 2; // 从第一行开始写入
+		try {
+			workbook = Workbook.createWorkbook(new File(filePath)); // 创建Excel文件
+			sheet = workbook.createSheet(sheetName, 0); // 创建名为 sheetName 的工作簿
+
+			this.writeCol(sheet, columnName, 1); // 首先将列名写入
+
+			// 写入时间
+			Vector col2 = new Vector(); // 用以保存一行数据
+			col2.add("统计时间-:"+time1+"到"+time2);
+			this.writeCol(sheet, col2, 0);
+			// 将结果集写入
+			for (int i=0; i<aa.size(); i++){
+				Vector col = new Vector(); // 用以保存一行数据
+
+				for (int j = 0; j < aa.get(i).size(); j++) { // 将一行内容保存在col中
+					col.add(aa.get(i).get(j));
+				}
+				// 写入Excel
+				this.writeCol2(sheet, col, rowNum++);
+			}
+
+		} catch (Exception e) {
+			e.printStackTrace();
+		} finally {
+			try {
+				// 关闭
+				workbook.write();
+				workbook.close();
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+		}
+	}
+
+	public void WriteExcel5(ArrayList<ArrayList<String>> aa, ArrayList<String> al, ArrayList<String> al2, ArrayList<String> al_1, String filePath, String sheetName,
+							Vector columnName, String time1, String time2, String place) {
+		WritableWorkbook workbook = null;
+		WritableSheet sheet = null;
+
+		int rowNum = 3; // 从第四行开始写入具体数据
+		try {
+			workbook = Workbook.createWorkbook(new File(filePath)); // 创建Excel文件
+			sheet = workbook.createSheet(sheetName, 0); // 创建名为 sheetName 的工作簿
+
+			this.writeCol(sheet, columnName, 1); // 首先第二行将列名写入
+
+			// 写入时间
+			Vector col2 = new Vector(); // 用以保存一行数据
+			col2.add("统计时间-:"+time1+"到"+time2);
+			col2.add(" ");
+			col2.add(" ");
+			col2.add(" ");
+			col2.add(" ");
+			col2.add("订单号:"+place);
+			this.writeCol(sheet, col2, 0);    // 第一行写入时间、订单号
+			// 将结果集写入
+			for (int i=0; i<aa.size(); i++){
+				Vector col = new Vector(); // 用以保存一行数据
+				for (int j = 0; j < aa.get(i).size(); j++) { // 将一行内容保存在col中
+					col.add(aa.get(i).get(j));
+				}
+				// 写入Excel
+				this.writeCol2(sheet, col, rowNum++);
+			}
+
+			Vector col3 = new Vector();
+			col3.add("-价格");
+			for (int j=0; j<al.size(); j++){
+				col3.add(al.get(j).toString());
+			}
+			this.writeCol2(sheet, col3, 2);
+
+			Vector col4 = new Vector();
+			col4.add("剩余数-");
+			for (int j=0; j<al2.size(); j++){
+				col4.add(al2.get(j).toString());
+			}
+			this.writeCol2(sheet, col4, rowNum+1);
+
+			Vector col5 = new Vector();
+			col5.add("走货数-");
+			for (int j=0; j<al_1.size(); j++){
+				col5.add(al_1.get(j).toString());
+			}
+			this.writeCol2(sheet, col5, rowNum);
+		} catch (Exception e) {
+			e.printStackTrace();
+		} finally {
+			try {
+				// 关闭
+				workbook.write();
+				workbook.close();
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+		}
+	}
+
+	/***
+	 * 将数组写入工作簿
+	 * 
+	 * @param sheet
+	 *            要写入的工作簿
+	 * @param col
+	 *            要写入的数据数组
+	 * @param rowNum
+	 *            要写入哪一行
+	 * @throws WriteException
+	 * @throws RowsExceededException
+	 */
+	private void writeCol(WritableSheet sheet, Vector col, int rowNum)
+			throws RowsExceededException, WriteException {
+		int size = col.size(); // 获取集合大小
+
+		for (int i = 0; i < size; i++) { // 写入每一列
+			Label label = new Label(i, rowNum, (String) col.get(i));
+			sheet.addCell(label);
+		}
+	}
+
+	// 处理工号和姓名的算法
+	private void writeCol2(WritableSheet sheet, Vector col, int rowNum)
+			throws RowsExceededException, WriteException {
+		int size = col.size(); // 获取集合大小
+
+		for (int i = 0; i < size; i++) { // 写入每一列
+			if(i == 0) {
+				String name1 = (String) col.get(i);
+				int n = name1.indexOf("-");
+				String name2 = name1.substring(0, n);
+				Label label = new Label(i, rowNum, name2);
+				sheet.addCell(label);
+			}else{
+				Label label = new Label(i, rowNum, (String) col.get(i));
+				sheet.addCell(label);
+			}
+		}
+	}
+}

+ 50 - 0
Data.java

@@ -0,0 +1,50 @@
+package com.happy.Model;
+
+public class Data {
+
+    public double bm;
+    public String dataTime;
+    public Integer frequency;
+    public String pointId;
+    public Integer status;
+
+    public double getBm() {
+        return bm;
+    }
+
+    public void setBm(double bm) {
+        this.bm = bm;
+    }
+
+    public String getDataTime() {
+        return dataTime;
+    }
+
+    public void setDataTime(String dataTime) {
+        this.dataTime = dataTime;
+    }
+
+    public Integer getFrequency() {
+        return frequency;
+    }
+
+    public void setFrequency(Integer frequency) {
+        this.frequency = frequency;
+    }
+
+    public String getPointId() {
+        return pointId;
+    }
+
+    public void setPointId(String pointId) {
+        this.pointId = pointId;
+    }
+
+    public Integer getStatus() {
+        return status;
+    }
+
+    public void setStatus(Integer status) {
+        this.status = status;
+    }
+}

+ 394 - 0
DataClient.java

@@ -0,0 +1,394 @@
+package testExport;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+import com.happy.Model.HistoryBm;
+import com.happy.Model.QueryUrlEnum;
+import com.happy.Unitil_elc.*;
+import com.happy.common.wx.WxUtil;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class DataClient {
+
+    static String token = "c19ac221e0504552b6c2ebed4b2b069b";
+
+    public static void main(String[] args) {
+        getToken();
+        //System.out.println(getPowerLastHistoryCumulant("NCJT210826009061"));
+        //String orderNo = WxUtil.mchOrderNo();
+        //System.out.println(recharege("HZJH201901220010", orderNo, "1"));
+        System.out.println(getAccountInfo("NCJT210826002156".replace("\n", "")));
+        //System.out.println(recharege("336211427165", orderNo, "0.1"));
+//        Gson gson = new Gson();
+//        com.alibaba.fastjson.JSONObject mess = DataClient.recharege("336211427165", orderNo, "0.1");
+//        HashMap<String, String> userMap = gson.fromJson(mess.toString(), new TypeToken<HashMap<String, String>>() {}.getType());
+//        String msg = userMap.get("msg");
+//        if (msg.equals("请求成功")) {
+//            System.out.println("成功");
+//        }
+        //System.out.println(getAccountInfo("NCJT210826001025"));
+        //System.out.println(getPowerLastHistoryCumulantw("336211429210"));
+        //System.out.println(queryPowerRealTimeData("NCJT210826010145"));
+        //System.out.println(queryDataCenter());
+        //System.out.println(getHistoryCumulant());
+//        getUserAccountInfo();
+//        queryBuildingUsed();
+//        queryBuilding();
+//        queryDataCenter();
+//        customerRegister();
+//        getAccountInfo();
+//        customerInfoModify();
+//        getUserAccountInfo();
+//        recharege();
+//        disconnect();
+//          powerRealData();
+//        getPowerLastHistoryCumulant();
+//        getHistoryCumulant();
+//        getMonthBill();
+//        getLastHistoryCumulant();
+
+    }
+
+    /* 除获取token外的所有请求都需要带有token数据,demo中简单起见未做token的保存处理,实际使用中请自行实现 */
+    public static void getToken() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("operatorSecret", Globals.OPERATOR_SECRET);
+        try {
+           JSONObject jsonObject = queryData(QueryUrlEnum.QUERY_TOKEN.getUrl(), map, null);
+           String data = jsonObject.getString("data");
+           JSONObject dataObject = JSONObject.parseObject(data);
+           token = dataObject.getString("accessToken");
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    // 查询建筑日/小时用量数据
+    public static void queryBuildingUsed() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("buildingCode", "JHEQ-2#");//建筑编码
+        map.put("type", "1");//数据类型
+        map.put("dataTime", "2021090915");//数据时间
+        try {
+            queryData(QueryUrlEnum.QUERY_BUILDING_USED.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    // 查询建筑信息
+    public static void queryBuilding() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("buildingCode", "JHEQ-1#");//建筑编码
+        map.put("dataCenterCode", "000000");//数据中心编码
+        try {
+            queryData(QueryUrlEnum.QUERY_BUILDING.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    // 查询数据中心信息
+    public static JSONObject queryDataCenter() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("dataCenterCode", "000001");//数据中心编码
+        JSONObject jsonObject = null;
+        try {
+            jsonObject = queryData(QueryUrlEnum.QUERY_DATACENTER.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return jsonObject;
+    }
+
+
+    // 电费月账单(水费月账单参数相同,只有接口不同,)
+    public static JSONObject getMonthBill(String user_id, String months) {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("userId", user_id);//户号"HZJH201901220010"
+        map.put("queryTimes", months);//查询时间点 [yyyy-MM,yyyy-MM……]
+        Object money = null;
+        try {
+            return queryData(QueryUrlEnum.POWER_MONTH_BILL.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+            return null;
+        }
+    }
+
+    // 账户信息
+    public static JSONObject getAccountInfo(String user_id) {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("userId", user_id);//户号
+        try {
+            return queryData(QueryUrlEnum.ACCOUNT_INFO.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+            return null;
+        }
+    }
+
+    // 用户信息
+    public static void getUserAccountInfo() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("userId", "HZJH201903190022");//户号
+        try {
+            queryData(QueryUrlEnum.USER_INFO.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    // 用户注册
+    public static void customerRegister() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("userId", "HZJH201903190022");//户号 注意不可重复
+        map.put("phone", "18888888888");//手机号
+        map.put("time", "2019-03-06 14:00:00");//注册时间
+        map.put("name", "李华");//名称
+        map.put("linkman", "李华");//联系人
+        try {
+            queryData(QueryUrlEnum.ACCOUNT_REGISTER.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    // 用户充值
+    public static JSONObject recharege(String user_id, String orderNo, String money) {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("userId", user_id);//户号 注意不可重复
+        map.put("tradeNo", orderNo);//交易号 一个交易号只能充值一次"2018090101010103"
+        map.put("money", money);//金额
+        try {
+            return queryData(QueryUrlEnum.ACCOUNT_RECHARGE.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+            return null;
+        }
+    }
+
+    // 用户信息修改
+    public static void customerInfoModify() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("userId", "HZJH201903190022");//户号 注意不可重复
+        map.put("phone", "18888888888");//手机号
+        map.put("linkman", "Li-Hua");//注册时间
+        map.put("name", "李华");//名称
+        try {
+            queryData(QueryUrlEnum.ACCOUNT_MODIFY.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    // 历史数据
+    public static JSONObject getHistoryCumulant(String pointid, String startTime,
+                                                String endTime) {
+        JSONObject jsonObject = null;
+        HashMap<String, String> map = new HashMap<>();
+        map.put("pointId", pointid);//表计编码
+        map.put("startTime", startTime);//开始时间
+        map.put("endTime", endTime);//结束时间
+        map.put("pointType", "1");//设备类型信息:1电表;2水表
+        map.put("type", "1");//数据类型   0, 所有(可以理解为,最小采集周期间隔的数据,如小时数据); 1, 按天,采集周期为天的数据
+        try {
+            jsonObject = queryData(QueryUrlEnum.HISTORY_CUMULANT.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return jsonObject;
+    }
+
+    // 电表最新一条历史数据
+    public static JSONObject getPowerLastHistoryCumulant(String pointid) {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("pointId", pointid);//表计编码
+        map.put("pointType", "1");
+        JSONObject jsonObject = null;
+        try {
+            jsonObject = queryData(QueryUrlEnum.LAST_HISTORY_CUMULANT.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return jsonObject;
+    }
+
+    // 水表最新一条历史数据
+    public static JSONObject getPowerLastHistoryCumulantw(String pointid) {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("pointId", pointid);//表计编码
+        map.put("pointType", "2");
+        JSONObject jsonObject = null;
+        try {
+            jsonObject = queryData(QueryUrlEnum.LAST_HISTORY_CUMULANT.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return jsonObject;
+    }
+
+
+    // 最新一条历史数据
+    public static void getLastHistoryCumulant() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("pointId", "00000090409190");//表计编码
+        map.put("pointType", "2");
+        try {
+            queryData(QueryUrlEnum.LAST_HISTORY_CUMULANT.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    // 拉合闸
+    public static void disconnect() {
+        HashMap<String, String> map = new HashMap<>();
+
+        map.put("pointId", "000000000001");//表计编号
+        map.put("operType", "1");//1.拉闸2.合闸
+        try {
+            queryData(QueryUrlEnum.REMOTE_DISCONNECT.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    // 电表实时信息  电表实时信息抄读时间较长,注意设置连接的超时时间
+    public static void powerRealData() {
+        String token = "23fff64f891e4bca8280224d916e789a";
+        HashMap<String, String> map = new HashMap<>();
+
+        map.put("pointId", "000000000001");//表计编号
+        try {
+            queryData(QueryUrlEnum.METER_REAL_INFO.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    // 电表实时信息  电表实时信息抄读时间较长,注意设置连接的超时时间
+    public static JSONObject queryPowerRealTimeData(String pointid) {
+        HashMap<String, String> map = new HashMap<>();
+
+        map.put("pointId", pointid);//表计编号
+        try {
+            return queryData(QueryUrlEnum.queryPowerRealTimeData.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+            return null;
+        }
+    }
+
+    // 查询用户信息
+    public static JSONObject queryChangedUserAccountInfo
+            (String startTime, String endTime, String pageIndex, String pageLimit){
+        HashMap<String, String> map = new HashMap<>();
+        map.put("startTime", startTime);
+        map.put("endTime", endTime);
+        map.put("pageIndex", pageIndex);
+        map.put("pageLimit", pageLimit);
+        JSONObject jsonObject = null;
+        try {
+            jsonObject = queryData(QueryUrlEnum.queryChangedUserAccountInfo.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return jsonObject;
+    }
+
+    // 查询用能单位能耗
+    public static JSONObject queryEnergyUnitUsed
+                 (String energyUnitId, String energyUnitType,
+                  String energyType, String circleType, String dataTime){
+        HashMap<String, String> map = new HashMap<>();
+        map.put("energyUnitId", energyUnitId);
+        map.put("energyUnitType", energyUnitType);
+        map.put("energyType", energyType);
+        map.put("circleType", circleType);
+        map.put("dataTime", dataTime);
+        JSONObject jsonObject = null;
+        try {
+            jsonObject = queryData(QueryUrlEnum.queryEnergyUnitUsed.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return jsonObject;
+    }
+
+    /**
+     * 请求数据
+     *
+     * @param path    请求接口
+     * @param dataMap 所需的数据Map
+     */
+    public static JSONObject queryData(String path, Map<String, String> dataMap, String token) throws Exception {
+        // 加密data部分
+        String encode = CodeUtil.dataEncode(JSON.toJSONString(dataMap), Globals.DATA_SECRET, Globals.DATA_SECRET_IV);
+        /*组装必要参数 start */
+        String seq = "0001";
+        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
+        Map<String, String> map = new HashMap<>();
+        map.put("operatorId", Globals.OPERATOR_ID);
+        map.put("data", encode);
+        map.put("timeStamp", timeStamp);
+        map.put("seq", seq);
+        /*组装必要参数 end */
+        if (encode == null) return null;
+
+        /*生成签名 start*/
+        // 为防止+在收发过程中被变成空格,将加密后的密文中的所有空格替换一下
+        // 需要签名的参数: operatorId + 加密后的data + 时间戳 + 自增序列
+        String signSrc = Globals.OPERATOR_ID + encode.replaceAll(" ", "+") + timeStamp + seq;
+        String sig = CodeUtil.getSign(signSrc, Globals.SIGN_KEY);
+        //将签名放入参数Map
+        map.put("sig", sig);
+        /*生成签名 start*/
+        /*执行请求,使用可以附加token的doPost方*/
+        HttpClientHelper instance = HttpClientHelper.getInstance();
+        //token也可以放进参数列表
+        String result = instance.doPost(Globals.URL_PREFIX + (path.startsWith("/") ? path : ("/" + path)), map, token);
+        if (StringUtil.isEmpty(result)) return null;
+
+        /*解析数据 start*/
+        JSONObject jsonObject = JSON.parseObject(result);
+        // 失败
+        if (!"0".equals(jsonObject.getString("ret"))) {
+            printJsonMessage("send Error:", jsonObject);
+            return null;
+        }
+        // 验签,注意生成签名的参数顺序应和发送时一样
+        // 为防止'+'在收发过程中被变成' ',将加密后的密文中的所有空格替换一下
+        String resultSigStr = jsonObject.getString("operatorId") + jsonObject.getString("data").replaceAll(" ", "+")
+                + jsonObject.getString("msg") + jsonObject.getString("ret");
+        String resultSig = CodeUtil.getSign(resultSigStr, Globals.SIGN_KEY);
+        if (StringUtil.isNotEmpty(jsonObject.getString("sig")) && jsonObject.getString("sig").equals(resultSig)) {
+            // 解密数据,需要数据秘钥和秘钥初始化向量
+            String data = CodeUtil.dataDecode(jsonObject.getString("data"), Globals.DATA_SECRET, Globals.DATA_SECRET_IV);
+            jsonObject.put("data", data);
+        }
+        /*解析数据 end*/
+        // 打印 or 其他操作
+//        printJsonMessage("Send Message:", map);
+//        printJsonMessage("Receive Message:", result);
+//        printJsonMessage("Decode Message:", jsonObject);
+        return jsonObject;
+    }
+
+    public static void printJsonMessage(String prefix, Object obj) {
+        System.out.println(prefix + JsonUtil.JsonFormart(JSON.toJSONString(obj)));
+    }
+
+}

+ 113 - 0
Detail_elc.java

@@ -0,0 +1,113 @@
+package com.happy.Model;
+
+public class Detail_elc {
+
+    public Integer id;
+    public String build;
+    public String dom;
+    public String pointid;
+    public String dataTime;
+    public double bm;
+    public double use_elc;
+    public double usable_elc;
+    public double recharge_elc;
+    public Integer use_state;
+    public Integer usable_state;
+    public Integer re_state;
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public String getBuild() {
+        return build;
+    }
+
+    public void setBuild(String build) {
+        this.build = build;
+    }
+
+    public String getDom() {
+        return dom;
+    }
+
+    public void setDom(String dom) {
+        this.dom = dom;
+    }
+
+    public String getPointid() {
+        return pointid;
+    }
+
+    public void setPointid(String pointid) {
+        this.pointid = pointid;
+    }
+
+    public String getDataTime() {
+        return dataTime;
+    }
+
+    public void setDataTime(String dataTime) {
+        this.dataTime = dataTime;
+    }
+
+    public double getBm() {
+        return bm;
+    }
+
+    public void setBm(double bm) {
+        this.bm = bm;
+    }
+
+    public double getUse_elc() {
+        return use_elc;
+    }
+
+    public void setUse_elc(double use_elc) {
+        this.use_elc = use_elc;
+    }
+
+    public double getUsable_elc() {
+        return usable_elc;
+    }
+
+    public void setUsable_elc(double usable_elc) {
+        this.usable_elc = usable_elc;
+    }
+
+    public double getRecharge_elc() {
+        return recharge_elc;
+    }
+
+    public void setRecharge_elc(double recharge_elc) {
+        this.recharge_elc = recharge_elc;
+    }
+
+    public Integer getUse_state() {
+        return use_state;
+    }
+
+    public void setUse_state(Integer use_state) {
+        this.use_state = use_state;
+    }
+
+    public Integer getUsable_state() {
+        return usable_state;
+    }
+
+    public void setUsable_state(Integer usable_state) {
+        this.usable_state = usable_state;
+    }
+
+    public Integer getRe_state() {
+        return re_state;
+    }
+
+    public void setRe_state(Integer re_state) {
+        this.re_state = re_state;
+    }
+}

+ 50 - 0
Detail_elc2.java

@@ -0,0 +1,50 @@
+package com.happy.Model;
+
+public class Detail_elc2 {
+
+    public Integer id;
+    public String build;
+    public String dom;
+    public String dataTime;
+    public String use_elc;
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public String getBuild() {
+        return build;
+    }
+
+    public void setBuild(String build) {
+        this.build = build;
+    }
+
+    public String getDom() {
+        return dom;
+    }
+
+    public void setDom(String dom) {
+        this.dom = dom;
+    }
+
+    public String getDataTime() {
+        return dataTime;
+    }
+
+    public void setDataTime(String dataTime) {
+        this.dataTime = dataTime;
+    }
+
+    public String getUse_elc() {
+        return use_elc;
+    }
+
+    public void setUse_elc(String use_elc) {
+        this.use_elc = use_elc;
+    }
+}

+ 50 - 0
Device.java

@@ -0,0 +1,50 @@
+package com.happy.Model;
+
+public class Device {
+
+    public int id;
+    public String device_code;
+    public String device_campus;
+    public String device_build;
+    public String device_dom;
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getDevice_code() {
+        return device_code;
+    }
+
+    public void setDevice_code(String device_code) {
+        this.device_code = device_code;
+    }
+
+    public String getDevice_campus() {
+        return device_campus;
+    }
+
+    public void setDevice_campus(String device_campus) {
+        this.device_campus = device_campus;
+    }
+
+    public String getDevice_build() {
+        return device_build;
+    }
+
+    public void setDevice_build(String device_build) {
+        this.device_build = device_build;
+    }
+
+    public String getDevice_dom() {
+        return device_dom;
+    }
+
+    public void setDevice_dom(String device_dom) {
+        this.device_dom = device_dom;
+    }
+}

+ 12 - 0
DictionaryCompare.java

@@ -0,0 +1,12 @@
+package com.happy.Until.weixin;
+
+import java.util.Comparator;
+
+/**
+ * 按字典序排序
+ */
+class DictionaryCompare implements Comparator<String> {
+	public int compare(String o1, String o2) {
+		return o1.compareTo(o2);
+	}
+}

+ 68 - 0
ET.java

@@ -0,0 +1,68 @@
+package com.happy.Model;
+
+public class ET {
+
+    public Integer ret;
+    public String msg;
+    public String sig;
+    public Data data;
+    public Integer resultCode;
+    public String ok;
+    public String operatorId;
+
+    public Integer getRet() {
+        return ret;
+    }
+
+    public void setRet(Integer ret) {
+        this.ret = ret;
+    }
+
+    public String getMsg() {
+        return msg;
+    }
+
+    public void setMsg(String msg) {
+        this.msg = msg;
+    }
+
+    public String getSig() {
+        return sig;
+    }
+
+    public void setSig(String sig) {
+        this.sig = sig;
+    }
+
+    public Data getData() {
+        return data;
+    }
+
+    public void setData(Data data) {
+        this.data = data;
+    }
+
+    public Integer getResultCode() {
+        return resultCode;
+    }
+
+    public void setResultCode(Integer resultCode) {
+        this.resultCode = resultCode;
+    }
+
+    public String getOk() {
+        return ok;
+    }
+
+    public void setOk(String ok) {
+        this.ok = ok;
+    }
+
+    public String getOperatorId() {
+        return operatorId;
+    }
+
+    public void setOperatorId(String operatorId) {
+        this.operatorId = operatorId;
+    }
+}

+ 525 - 0
Elec.java

@@ -0,0 +1,525 @@
+package com.happy.action;
+
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+import com.happy.Model.*;
+import com.happy.Model.weixin.PayResult;
+import com.happy.Model.weixin.WechatUnifiedOrder;
+import com.happy.Unitil_nsh.GetHttpParam;
+import com.happy.Until.HttpUtils;
+import com.happy.Until.ResUtil;
+import com.happy.Until.ResponseUtil;
+import com.happy.Until.Time.OnlineTime;
+import com.happy.Until.weixin.EndPay;
+import com.happy.Until.weixin.JaxbUtil;
+import com.happy.Until.weixin.PayWxUtil;
+import com.happy.Until.weixin.TongYiReturn;
+import com.happy.common.http.HttpsClient;
+import com.happy.common.wx.WxUtil;
+import com.happy.service.*;
+import com.opensymphony.xwork2.ActionSupport;
+import net.sf.json.JSONObject;
+import org.apache.struts2.ServletActionContext;
+import org.apache.struts2.interceptor.ServletRequestAware;
+import testExport.DataClient;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import java.io.BufferedReader;
+import java.io.PrintWriter;
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+public class Elec extends ActionSupport implements ServletRequestAware {
+
+    private HttpServletRequest request;
+    public HttpServletResponse response;
+
+    public String code;
+    public String stu_number;
+    public String re_time;
+    public String roomSelect;
+    public String ord_no;
+    public String out_no;
+    public String status;
+    public String dom;
+
+    @Resource
+    public UserService userService;
+    @Resource
+    public ConsumeService consumeService;
+    @Resource
+    public RechargeService rechargeService;
+    @Resource
+    public WxMenuService wxMenuService;
+    @Resource
+    public ElecService elecService;
+
+    public HttpServletRequest getRequest() {
+        return request;
+    }
+
+    public void setRequest(HttpServletRequest request) {
+        this.request = request;
+    }
+
+    public void setServletRequest(HttpServletRequest request) {
+        this.request = request;
+    }
+
+    public HttpServletResponse getResponse() {
+        return response;
+    }
+
+    public void setResponse(HttpServletResponse response) {
+        this.response = response;
+    }
+
+    public String getCode() {
+        return code;
+    }
+
+    public void setCode(String code) {
+        this.code = code;
+    }
+
+    public String getStu_number() {
+        return stu_number;
+    }
+
+    public void setStu_number(String stu_number) {
+        this.stu_number = stu_number;
+    }
+
+    public String getRe_time() {
+        return re_time;
+    }
+
+    public void setRe_time(String re_time) {
+        this.re_time = re_time;
+    }
+
+    public String getRoomSelect() {
+        return roomSelect;
+    }
+
+    public void setRoomSelect(String roomSelect) {
+        this.roomSelect = roomSelect;
+    }
+
+    public String getOrd_no() {
+        return ord_no;
+    }
+
+    public void setOrd_no(String ord_no) {
+        this.ord_no = ord_no;
+    }
+
+    public String getOut_no() {
+        return out_no;
+    }
+
+    public void setOut_no(String out_no) {
+        this.out_no = out_no;
+    }
+
+    public String getStatus() {
+        return status;
+    }
+
+    public void setStatus(String status) {
+        this.status = status;
+    }
+
+    public String getDom() {
+        return dom;
+    }
+
+    public void setDom(String dom) {
+        this.dom = dom;
+    }
+
+    public String stu_dom() throws Exception {
+        JSONObject resultJson = new JSONObject();
+        List<Users> user = userService.selectByStu(stu_number);
+        if (user == null){
+            resultJson.put("msg", "未绑定用户信息");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        String school = user.get(0).getCampus();
+        String room = user.get(0).getDom();
+        if (school==null || room==null){
+            resultJson.put("msg", "未绑定宿舍");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        String data = school.concat(room);
+        resultJson.put("msg", "1");
+        resultJson.put("dom", data);
+        ResUtil.write(resultJson, ServletActionContext.getResponse());
+        return null;
+    }
+
+    public String Pay() throws Exception {
+        JSONObject resultJson = new JSONObject();
+        if (roomSelect==null){
+            resultJson.put("mess", "请选择房间号!");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        String school = roomSelect.substring(0, 5);
+        String room = roomSelect.substring(5);
+        List<Build_elec> spl = elecService.queryUser_id(school, room);
+        if (spl == null){
+            resultJson.put("mess", "未查询到户号!");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        String user_id = spl.get(0).getUser_id();
+        HttpSession session = request.getSession();
+        Gson gson=new Gson();
+        System.out.println("房间号:"+room);
+        System.out.println("户号:"+user_id);
+        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
+                "appid="+ WeiXinUtil.appid_elc +
+                "&secret="+ WeiXinUtil.screct_elc +
+                "&js_code="+code+
+                "&grant_type=authorization_code";
+        if (code==null){
+            resultJson.put("mess", "code不能为空");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+        }
+        String jsons = HttpsClient.sendPost(url, "");
+        HashMap<String, String> userMap = gson.fromJson(jsons.toString(), new TypeToken<HashMap<String, String>>(){}.getType());
+        String open_id = "";
+        try{
+            open_id = userMap.get("openid").toString();
+
+        }catch (Exception e){
+            resultJson.put("mess", "code超时");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        List<Users> u = userService.queryByopenid(open_id);  // 查找是不是会员,不是会员不能充值
+        String num = request.getParameter("num");
+        session.setAttribute("num", num); // 存入金额session中
+        if (u != null  ) {
+            String ip = request.getParameter("ip");
+            double money = Double.parseDouble(request.getParameter("num"));
+            int a = (int) (money * 100);
+            WechatUnifiedOrder w = new WechatUnifiedOrder();
+            w.setAppid(WeiXinUtil.appid);
+            w.setAttach("chuanghai");
+            w.setBody("chuanghai");
+            w.setMch_id(WeiXinUtil.account_elc);
+            w.setNonce_str(PayWxUtil.getNonceStr());// 随机支付串
+            w.setNotify_url(WeiXinUtil.ip + "elpayResulet.action");// 支付结果回调地址
+            w.setOpenid(open_id);
+            String orderNo = WxUtil.mchOrderNo();
+            w.setOut_trade_no(orderNo);
+            w.setSpbill_create_ip(ip);
+            w.setTotal_fee(a);
+            w.setTrade_type("JSAPI");
+            Map<String, String> params = new HashMap<String, String>();
+            params.put("attach", w.getAttach());
+            params.put("appid", w.getAppid());
+            params.put("mch_id", w.getMch_id());
+            params.put("nonce_str", w.getNonce_str());
+            params.put("body", w.getBody());
+            params.put("out_trade_no", w.getOut_trade_no());
+            params.put("total_fee", w.getTotal_fee() + "");
+            params.put("spbill_create_ip", w.getSpbill_create_ip());
+            params.put("notify_url", w.getNotify_url());
+            params.put("trade_type", w.getTrade_type());
+            params.put("openid", w.getOpenid());
+            w.setSign(PayWxUtil.getSign(params, WeiXinUtil.APIid_elc));
+            params.put("sign", w.getSign());
+            String retXml = JaxbUtil.getRequestXml(params);
+            String msg = HttpUtils.post("https://api.mch.weixin.qq.com/pay/unifiedorder", retXml);
+            System.out.println("msg: "+ msg);
+            if (msg.indexOf("FAIL") > -1) {
+                JSONObject json = new JSONObject();
+                json.put("pay", "error");
+                ResponseUtil.write(json, ServletActionContext.getResponse());
+                return null;
+            } else {
+                JaxbUtil requestBinder = new JaxbUtil(TongYiReturn.class, JaxbUtil.CollectionWrapper.class);
+                TongYiReturn to = requestBinder.fromXml(msg);
+                if (to.getReturn_code().equals("SUCCESS") && to.getResult_code().equals("SUCCESS")) {
+                    EndPay pay = new EndPay();
+                    pay.setAppId(WeiXinUtil.appid_elc);
+                    pay.setSignType("MD5");
+                    pay.setTimeStamp(System.currentTimeMillis() / 1000 + "");
+                    pay.setPrepay_id(to.getPrepay_id());
+                    pay.setNonceStr(PayWxUtil.getNonceStr());
+                    Map<String, String> requestMap = new HashMap<String, String>();
+                    requestMap.put("appId", pay.getAppId());
+                    requestMap.put("timeStamp", pay.getTimeStamp());
+                    requestMap.put("nonceStr", pay.getNonceStr());
+                    requestMap.put("package", "prepay_id=" + pay.getPrepay_id());
+                    requestMap.put("signType", "MD5");
+                    pay.setPaySign(PayWxUtil.getSign(requestMap, WeiXinUtil.APIid_elc));
+                    // requestMap.put("sign",pay.getPaySign());
+                    // String ret = JaxbUtil.getRequestXml(requestMap);
+                    // System.out.println(ret);
+                    JSONObject json = new JSONObject();
+                    json.put("pay", pay);
+                    ResUtil.write(json, ServletActionContext.getResponse());
+                    Recharge_elc pay1 = new Recharge_elc();
+                    SimpleDateFormat simp1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+                    String time = simp1.format(new Date());
+                    pay1.setOrder_num(orderNo);
+                    pay1.setStu_number(u.get(0).getStu_number());
+                    pay1.setAccount((double) a / 100);
+                    pay1.setUser_name(u.get(0).getUser_name());
+                    pay1.setState(0);
+                    pay1.setCard_number(u.get(0).getStu_number());
+                    pay1.setRe_time(time);
+                    pay1.setSchool(school);
+                    List<Build_elec> be = elecService.queryBuildByDom(room);
+                    pay1.setRoom(room);
+                    pay1.setBuild(be.get(0).getBuild());
+                    rechargeService.insertRecharge2(pay1);
+                    System.out.println("保存成功");
+                }
+            }
+        } else { // 说明不是会员
+            JSONObject json = new JSONObject();
+            json.put("pay", 1);
+            ResUtil.write(json, ServletActionContext.getResponse());
+        }
+        return null;
+    }
+
+    // 第五步:支付页面用户输完密码后微信会把支付结果回调到这里,我们根据需要存储支付记录,和执行不同的方法
+    public String payResulet() throws Exception { // 微信支付结果通知
+		System.out.println("进来了");
+		Gson gson = new Gson();
+        BufferedReader reader = null;// BufferedReader 字符输入流
+        reader = request.getReader();
+        String line = "";
+        String xmlString = null;
+        StringBuffer inputString = new StringBuffer();
+
+        while ((line = reader.readLine()) != null) {
+            inputString.append(line);
+        }
+        xmlString = inputString.toString();
+        request.getReader().close();
+
+        JaxbUtil requestBinder = new JaxbUtil(PayResult.class, PayResult.class);
+        PayResult result = requestBinder.fromXml(xmlString);// Xml到Java,用fromXML()方法
+
+        if (result.getResult_code().equals("SUCCESS")) { // 交易成功,支付结果转换为对象
+            String orderNo = result.getOut_trade_no();// 微信支付订单号
+            rechargeService.succRecharge2(orderNo);  // 修改支付状态为已支付
+            System.out.println("支付成功了");
+            System.out.println("result=" + result.toString());
+            System.out.println("订单号:"+orderNo);
+            Recharge_elc re = rechargeService.findPayElByNo(orderNo);// 根据 微信支付订单号 查找支付记录信息
+            System.out.println("订单号二:"+re.getOrder_num());
+            // 更新宿舍号
+            System.out.println("房间号:"+re.getSchool());
+            userService.updateDom(re.getSchool(), re.getBuild(), re.getRoom(), re.getStu_number());
+            if (re == null) { // 没有交易记录 发送失败消息给商家
+                String returnMsg = "<xml><return_code><![CDATA[fail]]></return_code><return_msg><![CDATA[error]]></return_msg></xml>";
+                HttpServletResponse response = ServletActionContext.getResponse();
+                response.setContentType("text/html;charset=utf-8");
+                PrintWriter out = response.getWriter();
+                out.println(returnMsg);
+                out.flush();
+                out.close();
+//				System.out.println("pay不为空");
+            } else { // 交易记录开始记录
+                // 获得交易支付成功用户的信息
+                List<Build_elec> be = elecService.queryUser_id(re.getSchool(), re.getRoom());
+                System.out.println("金额:"+re.getAccount());
+                try {
+                    // 充值到第三方
+                    DataClient.getToken();
+                    com.alibaba.fastjson.JSONObject mess = DataClient.recharege(be.get(0).getUser_id(), orderNo, String.valueOf(re.getAccount()));
+                    HashMap<String, String> userMap = gson.fromJson(mess.toString(), new TypeToken<HashMap<String, String>>() {}.getType());
+                    String msg = userMap.get("msg");
+                    System.out.println("msg: "+msg);
+                    if (msg.equals("请求成功")) {
+                        System.out.println("请求接口成功。。");
+                        rechargeService.succRecharge3(orderNo); // 修改到账状态
+                    }
+                }catch (Exception e){
+                    return null;
+                }
+                String returnMsg = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
+                HttpServletResponse response = ServletActionContext.getResponse();
+                response.setContentType("text/html;charset=utf-8");
+                PrintWriter out = response.getWriter();
+                out.println(returnMsg);
+                out.flush();
+                out.close(); // 发送成功消息给商家
+            }
+        }
+        return null;
+    }
+
+    public String pay_ns() throws Exception {
+        JSONObject resultJson = new JSONObject();
+        Gson gson = new Gson();
+        String orderNo = WxUtil.mchOrderNo();
+        if (roomSelect == null || roomSelect.equals("")){
+            resultJson.put("msg", "获取宿舍异常");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        String school = roomSelect.substring(0, 5);
+        String room = roomSelect.substring(5);
+        if (stu_number==null || stu_number.equals("")){
+            resultJson.put("msg", "学号不能为空");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        String mon = request.getParameter("num");
+        if (mon == null || mon.equals("")){
+            resultJson.put("msg", "获取金额异常");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
+                "appid="+ WeiXinUtil.appid_elcn +
+                "&secret="+ WeiXinUtil.screct_elcn +
+                "&js_code="+code+
+                "&grant_type=authorization_code";
+        if (code==null){
+            resultJson.put("mess", "code不能为空");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+        }
+        String jsons = HttpsClient.sendPost(url, "");
+        HashMap<String, String> userMap = gson.fromJson(jsons.toString(), new TypeToken<HashMap<String, String>>(){}.getType());
+        String open_id = "";
+        try{
+            open_id = userMap.get("openid").toString();
+        }catch (Exception e){
+            resultJson.put("mess", "code超时");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        double money = Double.parseDouble(mon);
+        int a = (int) (money * 100);
+        com.alibaba.fastjson.JSONObject json = elecService.payOrder(orderNo, "WeixinJXYL", null, "电费充值", a,
+                0, 0, a, null, null, null, null,
+                null, "附加数据", null, WeiXinUtil.ip + "elpayResuletNs.action", open_id);
+        List<Users> u = userService.selectByStu(stu_number);
+        Recharge_elc pay1 = new Recharge_elc();
+        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        String time = sf.format(new Date());
+        pay1.setOrder_num(orderNo);
+        pay1.setStu_number(stu_number);
+        pay1.setAccount((double) a / 100);
+        pay1.setUser_name(u.get(0).getUser_name());
+        pay1.setState(0);
+        pay1.setCard_number(stu_number);
+        pay1.setRe_time(time);
+        pay1.setSchool(school);
+        List<Build_elec> be = elecService.queryBuildByDom(room);
+        pay1.setRoom(room);
+        pay1.setBuild(be.get(0).getBuild());
+        pay1.setDay_time(time.substring(0, 10));
+        pay1.setPointid(be.get(0).getPointid());
+        rechargeService.insertRecharge2(pay1);
+        json.put("sub_openid", open_id);
+        json.put("sub_appid", WeiXinUtil.appid_elcn);
+        json.put("order", orderNo);
+        json.put("account", money);
+        json.put("stu_number", stu_number);
+        ResUtil.write(json, ServletActionContext.getResponse());
+        return null;
+    }
+
+    public String payResuletNs() throws Exception {
+        System.out.println("成功进入农商");
+        System.out.println("订单号:"+ord_no);
+        System.out.println(status);
+        JSONObject resultJson = new JSONObject();
+        Gson gson = new Gson();
+        if (status.equals("4")){
+            ResUtil.write("notify_success", ServletActionContext.getResponse());
+        }
+        if (status.equals("1") ){
+            rechargeService.succRecharge2(ord_no);  // 修改支付状态为已支付
+            Recharge_elc re = rechargeService.findPayElByNo(ord_no);// 根据 微信支付订单号 查找支付记录信息
+            List<Build_elec> be = elecService.queryUser_id(re.getSchool(), re.getRoom());
+            try {
+                if (re.getState()==2){
+                    ResUtil.write("notify_success", ServletActionContext.getResponse());
+                    return null;
+                }
+                // 充值到第三方
+                DataClient.getToken();
+                com.alibaba.fastjson.JSONObject mess = DataClient.recharege(be.get(0).getUser_id().replace("\n", "").replace("\r", ""), ord_no, String.valueOf(re.getAccount()));
+                HashMap<String, String> userMap = gson.fromJson(mess.toString(), new TypeToken<HashMap<String, String>>() {}.getType());
+                String msg = userMap.get("msg");
+                System.out.println("msg: "+msg);
+                if (msg.equals("请求成功")) {
+                    System.out.println("请求接口成功。。");
+                    rechargeService.succRecharge3(ord_no); // 修改到账状态
+                }
+                ResUtil.write("notify_success", ServletActionContext.getResponse());
+            }catch (Exception e){
+                ResUtil.write("notify_success", ServletActionContext.getResponse());
+                return null;
+            }
+        }
+        return null;
+    }
+
+    public String queyRecordEle() throws Exception {
+        JSONObject resultJson = new JSONObject();
+        if (stu_number!=null && re_time!=null) {
+            List<Recharge_elc> record = rechargeService.queryRecordByStu(stu_number, re_time);
+            if (record!=null) {
+                resultJson.put("mess", "返回成功");
+                resultJson.put("data", record);
+                ResUtil.write(resultJson, ServletActionContext.getResponse());
+            }
+            resultJson.put("mess", "未查到记录");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        resultJson.put("mess", "学号不能为空");
+        ResUtil.write(resultJson, ServletActionContext.getResponse());
+        return null;
+    }
+
+    // 查询每天电费使用量
+    public String queryDayPower() throws Exception {
+        JSONObject resultJson = new JSONObject();
+        List<String> dateList = new ArrayList<>();
+        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
+        for (int i=-2; i>-9; i--){
+            Calendar calendar = Calendar.getInstance();
+            calendar.add(Calendar.DAY_OF_WEEK,i);
+            dateList.add(simpleDateFormat.format(calendar.getTime()));
+        }
+        StringBuilder sqlx = new StringBuilder(" and dataTime in (");
+        for (int i=0; i<dateList.size(); i++){
+            sqlx.append("'").append(dateList.get(i)).append("',");
+        }
+        sqlx.append("'')");
+        List<Detail_elc2> lists = elecService.queryDayPower(dom, sqlx.toString());
+        resultJson.put("code", "200");
+        resultJson.put("data", lists);
+        ResUtil.write(resultJson, ServletActionContext.getResponse());
+        return null;
+    }
+
+    public String time() throws Exception {
+        JSONObject resultJson = new JSONObject();
+        String time = OnlineTime.time();
+        resultJson.put("code", "200");
+        resultJson.put("data", time);
+        ResUtil.write(resultJson, ServletActionContext.getResponse());
+        return null;
+    }
+
+}

+ 55 - 0
ElecDao.java

@@ -0,0 +1,55 @@
+package com.happy.dao;
+
+import com.happy.Model.Build_elec;
+import com.happy.Model.Detail_elc;
+import com.happy.Model.Detail_elc2;
+import com.happy.Model.Recharge_elc;
+
+import java.util.List;
+
+public interface ElecDao {
+
+    public List<Build_elec> querySchool();
+
+    public List<Build_elec> queryBuild(String school);
+
+    public List<Build_elec> queryFloors(String school, String build);
+
+    public List<Build_elec> queryDom(String school, String build, String floors);
+
+    public List<Build_elec> queryUser_id(String school, String dom);
+
+    public List<Build_elec> queryBuildByPoint(String pointid);
+
+    public List<Build_elec> queryBuildByDom(String dom);
+
+    public List<Build_elec> queryAll();
+
+    public List<Detail_elc> queryDetailAll();
+
+    public List<Detail_elc> queryUse();
+
+    public List<Detail_elc> queryRe();
+
+    public int insertDetail(Detail_elc detail_elc);
+
+    public List<Detail_elc> queryByTimeAndPoint(String pointid, String dataTime);
+
+    public int updateUse(String pointid, String dataTime, double use_elc);
+
+    public int updateUseState(String pointid, String dataTime);
+
+    public List<Recharge_elc> queryByPointAndDay(String pointid, String day_time);
+
+    public int updateRe(String pointid, String dataTime, double recharge_elc);
+
+    public int updateReState(String pointid, String dataTime);
+
+    public List<Detail_elc> queryUsable();
+
+    public int updateUsable(String pointid, String dataTime, double usable_elc);
+
+    public int updateUsableState(String pointid, String dataTime);
+
+    public List<Detail_elc2> queryDayPower(String dom, String sqlx);
+}

+ 312 - 0
ElecDaoImpl.java

@@ -0,0 +1,312 @@
+package com.happy.dao.impl;
+
+import com.happy.Model.*;
+import com.happy.dao.ElecDao;
+import org.apache.commons.fileupload.util.LimitedInputStream;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.jdbc.core.BeanPropertyRowMapper;
+import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
+import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
+import org.springframework.stereotype.Repository;
+
+import java.util.List;
+
+@Repository("ElecDao")
+public class ElecDaoImpl implements ElecDao {
+
+    @Autowired
+    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
+
+    public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
+        return namedParameterJdbcTemplate;
+    }
+
+    public void setNamedParameterJdbcTemplate(
+            NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
+        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
+    }
+
+    public List<Build_elec> querySchool(){
+        String sql = "select distinct school as school from `build_elec`;";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        List<Build_elec> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Build_elec>(Build_elec.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public List<Build_elec> queryBuild(String school){
+        String sql = "select distinct build as build from `build_elec` where school=:school;";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("school", school);
+        List<Build_elec> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Build_elec>(Build_elec.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public List<Build_elec> queryFloors(String school, String build){
+        String sql = "select distinct floors as floors from `build_elec` where school=:school and build=:build;";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("school", school);
+        sps.addValue("build", build);
+        List<Build_elec> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Build_elec>(Build_elec.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public List<Build_elec> queryDom(String school, String build, String floors){
+        String sql = "select distinct dom as dom from `build_elec` where school=:school and build=:build and floors=:floors;";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("school", school);
+        sps.addValue("build", build);
+        sps.addValue("floors", floors);
+        List<Build_elec> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Build_elec>(Build_elec.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public List<Build_elec> queryUser_id(String school, String dom){
+        String sql = "select * from `build_elec` where school=:school and dom=:dom;";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("school", school);
+        sps.addValue("dom", dom);
+        List<Build_elec> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Build_elec>(Build_elec.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public List<Build_elec> queryBuildByDom(String dom){
+        String sql = "select * from `build_elec` where dom=:dom;";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("dom", dom);
+        List<Build_elec> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Build_elec>(Build_elec.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public List<Build_elec> queryBuildByPoint(String pointid){
+        String sql = "select * from `build_elec` where pointid=:pointid;";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("pointid", pointid);
+        List<Build_elec> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Build_elec>(Build_elec.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public List<Build_elec> queryAll(){
+        String sql = "select * from `build_elec` ";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        List<Build_elec> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Build_elec>(Build_elec.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public List<Detail_elc> queryDetailAll(){
+        String sql = "select * from `detail_elc` ";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        List<Detail_elc> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Detail_elc>(Detail_elc.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    // 查询未更新使用电费详情
+    public List<Detail_elc> queryUse(){
+        String sql = "select * from `detail_elc` where use_state=1 ";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        List<Detail_elc> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Detail_elc>(Detail_elc.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public int insertDetail(Detail_elc detail_elc){
+        String sql = "insert into detail_elc(build, dom, pointid, dataTime, bm) values(:build, :dom, :pointid, :dataTime, :bm)";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("build", detail_elc.getBuild());
+        sps.addValue("dom", detail_elc.getDom());
+        sps.addValue("pointid", detail_elc.getPointid());
+        sps.addValue("dataTime", detail_elc.getDataTime());
+        sps.addValue("bm", detail_elc.getBm());
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    public List<Detail_elc> queryByTimeAndPoint(String pointid, String dataTime){
+        String sql = "select * from `detail_elc` where pointid=:pointid and dataTime=:dataTime ";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("pointid", pointid);
+        sps.addValue("dataTime", dataTime);
+        List<Detail_elc> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Detail_elc>(Detail_elc.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public int updateUse(String pointid, String dataTime, double use_elc){
+        String sql = "update `detail_elc` set use_elc=:use_elc, use_state=2 where pointid=:pointid and dataTime=:dataTime and use_state=1 ";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("pointid", pointid);
+        sps.addValue("dataTime", dataTime);
+        sps.addValue("use_elc", use_elc);
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    public int updateUseState(String pointid, String dataTime){
+        String sql = "update `detail_elc` set use_state=2 where pointid=:pointid and dataTime=:dataTime and use_state=1 ";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("pointid", pointid);
+        sps.addValue("dataTime", dataTime);
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    // 查询每户每天充值记录
+    public List<Recharge_elc> queryByPointAndDay(String pointid, String day_time){
+        String sql = "select * from recharge_elc where pointid=:pointid and day_time=:day_time ";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("pointid", pointid);
+        sps.addValue("day_time", day_time);
+        List<Recharge_elc> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Recharge_elc>(Recharge_elc.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    // 查询未更新充值电费详情
+    public List<Detail_elc> queryRe(){
+        String sql = "select * from `detail_elc` where re_state=1 ";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        List<Detail_elc> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Detail_elc>(Detail_elc.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    // 更新电费充值详情
+    public int updateRe(String pointid, String dataTime, double recharge_elc){
+        String sql = "update `detail_elc` set recharge_elc=:recharge_elc, re_state=2 where pointid=:pointid and dataTime=:dataTime and re_state=1 ";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("pointid", pointid);
+        sps.addValue("dataTime", dataTime);
+        sps.addValue("recharge_elc", recharge_elc);
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    // 更新电费充值详情
+    public int updateReState(String pointid, String dataTime){
+        String sql = "update `detail_elc` set re_state=2 where pointid=:pointid and dataTime=:dataTime and re_state=1 ";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("pointid", pointid);
+        sps.addValue("dataTime", dataTime);
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    // 查询当日剩余电量详情
+    public List<Detail_elc> queryUsable(){
+        String sql = "select * from `detail_elc` where usable_state=1 ";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        List<Detail_elc> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Detail_elc>(Detail_elc.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    // 更新电费剩余详情
+    public int updateUsable(String pointid, String dataTime, double usable_elc){
+        String sql = "update `detail_elc` set usable_elc=:usable_elc, usable_state=2 where pointid=:pointid and dataTime=:dataTime and usable_state=1 ";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("pointid", pointid);
+        sps.addValue("dataTime", dataTime);
+        sps.addValue("usable_elc", usable_elc);
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    public int updateUsableState(String pointid, String dataTime){
+        String sql = "update `detail_elc` set usable_state=2 where pointid=:pointid and dataTime=:dataTime and usable_state=1 ";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("pointid", pointid);
+        sps.addValue("dataTime", dataTime);
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    public List<Detail_elc2> queryDayPower(String dom, String sqlx){
+        String sql = "select * from `detail_elc` where dom=:dom " + sqlx+" order by `dataTime` asc ";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("dom", dom);
+        List<Detail_elc2> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Detail_elc2>(Detail_elc2.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+}

+ 61 - 0
ElecService.java

@@ -0,0 +1,61 @@
+package com.happy.service;
+
+import com.alibaba.fastjson.JSONObject;
+import com.happy.Model.Build_elec;
+import com.happy.Model.Detail_elc;
+import com.happy.Model.Detail_elc2;
+import com.happy.Model.Recharge_elc;
+
+import java.util.List;
+
+public interface ElecService {
+
+    public List<Build_elec> querySchool();
+
+    public List<Build_elec> queryBuild(String school);
+
+    public List<Build_elec> queryFloors(String school, String build);
+
+    public List<Build_elec> queryDom(String school, String build, String floors);
+
+    public List<Build_elec> queryUser_id(String school, String dom);
+
+    public List<Build_elec> queryBuildByDom(String dom);
+
+    public List<Build_elec> queryBuildByPoint(String pointid);
+
+    public JSONObject payOrder(String outNo, String pmtTag, String pmtName, String ordName, Integer originalAmount,
+                               Integer discountAmount, Integer ignoreAmount, Integer tradeAmount, String tradeAccount,
+                               String tradeNo, String tradeResult, String remark, String authCode, String tag,
+                               String jumpUrl, String notifyUrl, String sub_openid);
+
+    public List<Build_elec> queryAll();
+
+    public List<Detail_elc> queryDetailAll();
+
+    public List<Detail_elc> queryUse();
+
+    public List<Detail_elc> queryRe();
+
+    public int insertDetail(Detail_elc detail_elc);
+
+    public List<Detail_elc> queryByTimeAndPoint(String pointid, String dataTime);
+
+    public int updateUse(String pointid, String dataTime, double use_elc);
+
+    public int updateUseState(String pointid, String dataTime);
+
+    public List<Recharge_elc> queryByPointAndDay(String pointid, String day_time);
+
+    public int updateRe(String pointid, String dataTime, double recharge_elc);
+
+    public int updateReState(String pointid, String dataTime);
+
+    public List<Detail_elc> queryUsable();
+
+    public int updateUsable(String pointid, String dataTime, double usable_elc);
+
+    public int updateUsableState(String pointid, String dataTime);
+
+    public List<Detail_elc2> queryDayPower(String dom, String sqlx);
+}

+ 228 - 0
ElecServiceImpl.java

@@ -0,0 +1,228 @@
+package com.happy.service.impl;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.happy.Model.*;
+import com.happy.Unitil_nsh.TLinx2Util;
+import com.happy.Unitil_nsh.TLinxAESCoder;
+import com.happy.Unitil_nsh.TestParams;
+import com.happy.common.wx.WxUtil;
+import com.happy.dao.ElecDao;
+import com.happy.service.ElecService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.util.Date;
+import java.util.List;
+import java.util.TreeMap;
+
+@Service("ElecService")
+public class ElecServiceImpl implements ElecService {
+
+    @Autowired
+    public ElecDao elecDao;
+
+    public ElecDao getElecDao() {
+        return elecDao;
+    }
+
+    public void setElecDao(ElecDao elecDao) {
+        this.elecDao = elecDao;
+    }
+
+    public List<Build_elec> querySchool(){
+        return elecDao.querySchool();
+    }
+
+    public List<Build_elec> queryBuild(String school){
+        return elecDao.queryBuild(school);
+    }
+
+    public List<Build_elec> queryFloors(String school, String build){
+        return elecDao.queryFloors(school, build);
+    }
+
+    public List<Build_elec> queryDom(String school, String build, String floors){
+        return elecDao.queryDom(school, build, floors);
+    }
+
+    public List<Build_elec> queryBuildByDom(String dom){
+        return elecDao.queryBuildByDom(dom);
+    }
+
+    public List<Build_elec> queryUser_id(String school, String dom){
+        return elecDao.queryUser_id(school, dom);
+    }
+
+    public List<Build_elec> queryBuildByPoint(String pointid){
+        return elecDao.queryBuildByPoint(pointid);
+    }
+
+    public JSONObject payOrder(String outNo, String pmtTag, String pmtName, String ordName, Integer originalAmount,
+                         Integer discountAmount, Integer ignoreAmount, Integer tradeAmount, String tradeAccount,
+                         String tradeNo, String tradeResult, String remark, String authCode, String tag,
+                         String jumpUrl, String notifyUrl,String sub_openid) {
+         JSONObject resultjson = new JSONObject();
+        // 初始化参数
+        String timestamp = new Date().getTime() / 1000 + "";    // 时间
+
+        try {
+
+            // 固定参数
+            TreeMap<String, String> postmap = new TreeMap<String, String>();    // 请求参数的map
+
+            postmap.put("open_id", TestParams.OPEN_ID);
+            postmap.put("timestamp", timestamp);
+
+            TreeMap<String, Object> datamap = new TreeMap<String, Object>();    // data参数的map
+
+            datamap.put("out_no", outNo);
+            datamap.put("pmt_tag", pmtTag);
+            datamap.put("pmt_name", pmtName);
+            datamap.put("ord_name", ordName);
+            datamap.put("original_amount", originalAmount + "");
+            datamap.put("discount_amount", discountAmount + "");
+            datamap.put("ignore_amount", ignoreAmount + "");
+            datamap.put("trade_amount", tradeAmount + "");
+            datamap.put("trade_account", tradeAccount);
+            datamap.put("trade_no", tradeNo);
+            datamap.put("trade_result", tradeResult);
+            datamap.put("remark", remark);
+            datamap.put("tag", tag);
+            datamap.put("notify_url", notifyUrl);
+            datamap.put("sub_appid", WeiXinUtil.appid_elcn);
+            datamap.put("sub_openid", sub_openid);
+            datamap.put("JSAPI","1");
+
+            /**
+             * 1 data字段内容进行AES加密,再二进制转十六进制(bin2hex)
+             */
+            TLinx2Util.handleEncrypt(datamap, postmap);
+
+            /**
+             * 2 请求参数签名 按A~z排序,串联成字符串,先进行sha1加密(小写),再进行md5加密(小写),得到签名
+             */
+            TLinx2Util.handleSign(postmap);
+
+            /**
+             * 3 请求、响应
+             */
+            String rspStr = TLinx2Util.handlePost(postmap, TestParams.PAYORDER);
+
+            //System.out.println("====post响应字符串= " + rspStr);
+
+            /**
+             * 4 验签  有data节点时才验签
+             */
+            JSONObject respObject = JSONObject.parseObject(rspStr);
+            //System.out.println("====响应错误码:" + respObject.get("errcode"));
+            //System.out.println("====响应错误提示:" + respObject.get("msg"));
+            //System.out.println(respObject);
+            Object dataStr = respObject.get("data");
+
+            if (!rspStr.isEmpty() && (dataStr != null)) {
+                if (TLinx2Util.verifySign(respObject)) {    // 验签成功
+
+                    /**
+                     * 5 AES解密,并hex2bin
+                     */
+                    String respData = TLinxAESCoder.decrypt(dataStr.toString(), TestParams.OPEN_KEY);
+
+                    System.out.println("=================响应data内容= " + respData);
+                    JSONObject jsonObject = JSONObject.parseObject(respData);
+                    System.out.println("appid: "+jsonObject);
+                    //Object tradeQrcode = jsonObject.get("trade_qrcode");
+                    resultjson.put("timeStamp", jsonObject.get("timeStamp"));
+                    resultjson.put("nonceStr", jsonObject.get("nonceStr"));
+                    resultjson.put("appId", jsonObject.get("appId"));
+                    resultjson.put("signType", jsonObject.get("signType"));
+                    resultjson.put("package", jsonObject.get("package"));
+                    resultjson.put("paySign", jsonObject.get("paySign"));
+                    return resultjson;
+                    //System.out.println("=================支付二维码地址= " + tradeQrcode.toString());
+                    //System.out.println("=================trade_result= " + jsonObject.get("trade_result").toString());
+
+                } else {
+                    //System.out.println("==========验签失败==========");
+                    return resultjson;
+                }
+            } else {
+                //System.out.println("==========没有返回data数据==========");
+                return resultjson;
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+            return resultjson;
+        }
+    }
+
+    public List<Build_elec> queryAll(){
+        return elecDao.queryAll();
+    }
+
+    public List<Detail_elc> queryDetailAll(){
+        return elecDao.queryDetailAll();
+    }
+
+    public List<Detail_elc> queryUse(){
+        return elecDao.queryUse();
+    }
+
+    public int updateUseState(String pointid, String dataTime){
+        return elecDao.updateUseState(pointid, dataTime);
+    }
+
+    public List<Detail_elc> queryRe(){
+        return elecDao.queryRe();
+    }
+
+    // 金额要设置两处
+    public static void main(String[] args) {
+        String orderNo = WxUtil.mchOrderNo();
+        System.out.println(orderNo);
+        JSONObject j = new ElecServiceImpl().payOrder(orderNo, "WeixinJXYL", null, "自定义订单名称", 1,
+                0, 0, 1, null, null, null, null,
+                null, "附加数据", null, "http://www.baidu.com/tlinx2apidemo1/callback/scanpay_cashier/payResult", "");
+        System.out.println(j);
+    }
+
+    public int insertDetail(Detail_elc detail_elc){
+        return elecDao.insertDetail(detail_elc);
+    }
+
+    public List<Detail_elc> queryByTimeAndPoint(String pointid, String dataTime){
+        return elecDao.queryByTimeAndPoint(pointid, dataTime);
+    }
+
+    public int updateUse(String pointid, String dataTime, double use_elc){
+        return elecDao.updateUse(pointid, dataTime, use_elc);
+    }
+
+    public List<Recharge_elc> queryByPointAndDay(String pointid, String day_time){
+        return elecDao.queryByPointAndDay(pointid,day_time);
+    }
+
+    public int updateRe(String pointid, String dataTime, double recharge_elc){
+        return elecDao.updateRe(pointid, dataTime, recharge_elc);
+    }
+
+    public int updateReState(String pointid, String dataTime){
+        return elecDao.updateReState(pointid,dataTime);
+    }
+
+    public List<Detail_elc> queryUsable(){
+        return elecDao.queryUsable();
+    };
+
+    public int updateUsable(String pointid, String dataTime, double usable_elc){
+        return elecDao.updateUsable(pointid,dataTime,usable_elc);
+    };
+
+    public int updateUsableState(String pointid, String dataTime){
+        return elecDao.updateUsableState(pointid, dataTime);
+    }
+
+    public List<Detail_elc2> queryDayPower(String dom, String sqlx){
+        return elecDao.queryDayPower(dom, sqlx);
+    }
+}

+ 23 - 0
ElecTotal.java

@@ -0,0 +1,23 @@
+package com.happy.Model;
+
+public class ElecTotal {
+
+    public String build;
+    public double use_size;
+
+    public String getBuild() {
+        return build;
+    }
+
+    public void setBuild(String build) {
+        this.build = build;
+    }
+
+    public double getUse_size() {
+        return use_size;
+    }
+
+    public void setUse_size(double use_size) {
+        this.use_size = use_size;
+    }
+}

+ 51 - 0
EndPay.java

@@ -0,0 +1,51 @@
+package com.happy.Until.weixin;
+/**
+ * 最后调用接口传的数据实体类;
+ * @author QT-666
+ *
+ */
+public class EndPay {
+      private String appId;//商户注册具有支付权限的公众号成功后即可获得
+      private String timeStamp;//当前的时间,其他详见时间戳规则
+      private String nonceStr;//随机字符串,不长于32位。推荐随机数生成算法
+      private String prepay_id;//统一下单接口返回的prepay_id参数值,提交格式如:prepay_id=***
+      private String signType;//签名算法,暂支持MD5
+      private String paySign;//签名,详见签名生成算法
+	public String getAppId() {
+		return appId;
+	}
+	public void setAppId(String appId) {
+		this.appId = appId;
+	}
+	public String getTimeStamp() {
+		return timeStamp;
+	}
+	public void setTimeStamp(String timeStamp) {
+		this.timeStamp = timeStamp;
+	}
+	public String getNonceStr() {
+		return nonceStr;
+	}
+	public void setNonceStr(String nonceStr) {
+		this.nonceStr = nonceStr;
+	}
+	public String getPrepay_id() {
+		return prepay_id;
+	}
+	public void setPrepay_id(String prepay_id) {
+		this.prepay_id = prepay_id;
+	}
+	public String getSignType() {
+		return signType;
+	}
+	public void setSignType(String signType) {
+		this.signType = signType;
+	}
+	public String getPaySign() {
+		return paySign;
+	}
+	public void setPaySign(String paySign) {
+		this.paySign = paySign;
+	}
+      
+}

+ 41 - 0
ErrorWaterPay.java

@@ -0,0 +1,41 @@
+package com.happy.Model;
+
+public class ErrorWaterPay {
+
+    public String build;
+    public String dom;
+    public String begin_time;
+    public String use_amount;
+
+    public String getBuild() {
+        return build;
+    }
+
+    public void setBuild(String build) {
+        this.build = build;
+    }
+
+    public String getDom() {
+        return dom;
+    }
+
+    public void setDom(String dom) {
+        this.dom = dom;
+    }
+
+    public String getBegin_time() {
+        return begin_time;
+    }
+
+    public void setBegin_time(String begin_time) {
+        this.begin_time = begin_time;
+    }
+
+    public String getUse_amount() {
+        return use_amount;
+    }
+
+    public void setUse_amount(String use_amount) {
+        this.use_amount = use_amount;
+    }
+}

+ 28 - 0
GetHttpParam.java

@@ -0,0 +1,28 @@
+package com.happy.Unitil_nsh;
+
+import com.alibaba.fastjson.JSONObject;
+import com.alibaba.fastjson.parser.Feature;
+
+import javax.servlet.http.HttpServletRequest;
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+
+public class GetHttpParam {
+
+    public static JSONObject getHttpParam(HttpServletRequest request){
+        //处理业务业务
+        JSONObject jsonObject = new JSONObject();
+        try {
+            BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
+            StringBuilder responseStrBuilder = new StringBuilder();
+            String inputStr;
+            while ((inputStr = streamReader.readLine()) != null)
+                responseStrBuilder.append(inputStr);
+
+            jsonObject = JSONObject.parseObject(responseStrBuilder.toString(), Feature.OrderedField);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return jsonObject;
+    }
+}

+ 18 - 0
GloablExceptionHandler.java

@@ -0,0 +1,18 @@
+package com.happy.interceptor;
+
+import com.alibaba.fastjson.JSONObject;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+@ControllerAdvice
+public class GloablExceptionHandler {
+
+    @ResponseBody
+    @ExceptionHandler(Exception.class)
+    public Object handleException(Exception e) {
+        String msg = e.getMessage();
+        JSONObject jsonObject = JSONObject.parseObject(msg);
+        return jsonObject;
+    }
+}

+ 34 - 0
Globals.java

@@ -0,0 +1,34 @@
+package testExport;
+
+
+/**
+ * 全局变量定义
+ */
+public interface Globals {
+
+    /**
+     * 运营商标识
+     */
+    String OPERATOR_ID = "000000001";
+    /**
+     * 运营商秘钥
+     */
+    String OPERATOR_SECRET = "lBej44bqTsoTKstf";
+    /**
+     * 运营商数据秘钥
+     */
+    String DATA_SECRET = "3huqwCCgGpwDs7zA";
+    /**
+     * 数据秘钥初始化向量
+     */
+    String DATA_SECRET_IV = "yrpc05EvAYB09KnQ";
+    /**
+     * 签名秘钥
+     */
+    String SIGN_KEY = "8eLaEDi53iHnwOVY";
+    /**
+     * 请求地址前缀1
+     */
+    String URL_PREFIX = "http://172.16.20.37:8181/ems-share-api";
+
+}

+ 32 - 0
HistoryBm.java

@@ -0,0 +1,32 @@
+package com.happy.Model;
+
+public class HistoryBm {
+
+    public double bm;
+    public String dataTime;
+    public String pointId;
+
+    public double getBm() {
+        return bm;
+    }
+
+    public void setBm(double bm) {
+        this.bm = bm;
+    }
+
+    public String getDataTime() {
+        return dataTime;
+    }
+
+    public void setDataTime(String dataTime) {
+        this.dataTime = dataTime;
+    }
+
+    public String getPointId() {
+        return pointId;
+    }
+
+    public void setPointId(String pointId) {
+        this.pointId = pointId;
+    }
+}

+ 350 - 0
HttpClientHelper.java

@@ -0,0 +1,350 @@
+package com.happy.Unitil_elc;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpHost;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.config.Registry;
+import org.apache.http.config.RegistryBuilder;
+import org.apache.http.config.SocketConfig;
+import org.apache.http.conn.socket.ConnectionSocketFactory;
+import org.apache.http.conn.socket.PlainConnectionSocketFactory;
+import org.apache.http.conn.ssl.NoopHostnameVerifier;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
+import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
+import org.apache.http.message.BasicHeader;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.protocol.HTTP;
+import org.apache.http.ssl.SSLContexts;
+import org.apache.http.util.EntityUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.net.ssl.SSLContext;
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+
+public class HttpClientHelper {
+
+
+    private static final Logger logger = LoggerFactory.getLogger(HttpClientHelper.class);
+    private static PoolingHttpClientConnectionManager poolConnManager = null;
+    private int maxTotalPool = 200;
+    private int maxConPerRoute = 20;
+    private int socketTimeout = 100000;
+    private int connectionRequestTimeout = 90000;
+    private int connectTimeout = 90000;
+
+    // 代理信息
+    public static String proxy_ip;
+    public static int proxy_port;
+
+    private static HttpClientHelper httpClientHelper = null;
+
+    private HttpClientHelper() {
+        init();
+    }
+
+    private static synchronized void syncInit() {
+        if (httpClientHelper == null) {
+            httpClientHelper = new HttpClientHelper();
+        }
+    }
+
+    public static HttpClientHelper getInstance(String proxyIp, Integer proxyPort) {
+        proxy_port = proxyPort;
+        proxy_ip = proxyIp;
+        if (httpClientHelper == null) {
+            syncInit();
+        }
+        return httpClientHelper;
+    }
+
+    public static HttpClientHelper getInstance() {
+        if (httpClientHelper == null) {
+            syncInit();
+        }
+        return httpClientHelper;
+    }
+
+    public PoolingHttpClientConnectionManager getConnManager() {
+        PoolingHttpClientConnectionManager cm = null;
+        try {
+            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
+            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE);
+            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http",
+                    PlainConnectionSocketFactory.getSocketFactory()).register("https",
+                    sslsf).build();
+            cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
+            // 将最大连接数增加到200
+            cm.setMaxTotal(maxTotalPool);
+            // 将每个路由基础的连接增加到20
+            cm.setDefaultMaxPerRoute(maxConPerRoute);
+        } catch (Exception e) {
+            logger.error("InterfacePhpUtilManager init Exception" + e.toString());
+        }
+        return cm;
+    }
+
+    public void init() {
+        try {
+            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
+            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE);
+            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http",
+                    PlainConnectionSocketFactory.getSocketFactory()).register("https",
+                    sslsf).build();
+            poolConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
+            // Increase max total connection to 200
+            poolConnManager.setMaxTotal(maxTotalPool);
+            // Increase default max connection per route to 20
+            poolConnManager.setDefaultMaxPerRoute(maxConPerRoute);
+            SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(socketTimeout).build();
+            poolConnManager.setDefaultSocketConfig(socketConfig);
+        } catch (Exception e) {
+            logger.error("InterfacePhpUtilManager init Exception" + e.toString());
+        }
+    }
+
+    public CloseableHttpClient getConnection() {
+        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout).setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
+        HttpClientBuilder httpClientBuilder = HttpClients.custom();
+        httpClientBuilder.setConnectionManager(poolConnManager).setDefaultRequestConfig(requestConfig);// set proxy
+        if (!StringUtil.isEmpty(proxy_ip) && proxy_port > 0) {
+            HttpHost proxy = new HttpHost(proxy_ip, proxy_port);
+            DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
+            httpClientBuilder.setRoutePlanner(routePlanner);
+        }
+
+        CloseableHttpClient httpClient = httpClientBuilder.build();
+        if (poolConnManager != null && poolConnManager.getTotalStats() != null) {
+            logger.info("now client pool " + poolConnManager.getTotalStats().toString());
+        }
+        return httpClient;
+    }
+
+    /**
+     * 发送 GET 请求(HTTP),不带输入数据
+     */
+    public String doGet(String url) {
+        return doGet(url, new HashMap<String,String>());
+    }
+
+    /**
+     * 发送 GET 请求(HTTP),K-V形式
+     */
+    public String doGet(String url, Map<String, String> params) {
+        String apiUrl = url;
+        StringBuffer param = new StringBuffer();
+        int i = 0;
+        for (String key : params.keySet()) {
+            if (i == 0) {
+                param.append("?");
+            } else {
+                param.append("&");
+            }
+            param.append(key).append("=").append(params.get(key));
+            i++;
+        }
+        apiUrl += param;
+        logger.info(apiUrl);
+        String result = null;
+        CloseableHttpClient httpClient = getConnection();
+        CloseableHttpResponse response = null;
+        HttpGet httpPost = null;
+        try {
+            httpPost = new HttpGet(apiUrl);
+            response = httpClient.execute(httpPost);
+            int status = response.getStatusLine().getStatusCode();
+            logger.info("http request url : " + url + " status : " + status);
+
+            if (status >= 200 && status < 300) {
+                HttpEntity entity = response.getEntity();
+                if (entity != null) {
+                    result = EntityUtils.toString(response.getEntity(), "UTF-8");
+                    logger.info("Request result : " + result);
+                }
+            }
+            EntityUtils.consume(response.getEntity());
+            response.close();
+            return result;
+
+        } catch (IOException e) {
+            logger.error(e.getMessage(), e);
+        } finally {
+            httpPost.releaseConnection();
+            if (response != null) {
+                try {
+                    EntityUtils.consume(response.getEntity());
+                    response.close();
+                } catch (IOException e) {
+                    logger.error(e.getMessage(), e);
+                }
+            }
+        }
+        return result;
+    }
+
+    public String doPost(String url) {
+        return doPost(url, new HashMap<String, String>());
+    }
+
+    /**
+     * 发送 POST json
+     *
+     * @param url 接口URL
+     */
+    public String doPostJson(String url, String jsonstr) {
+        String result = null;
+        HttpPost httpPost = new HttpPost(url);
+        CloseableHttpClient httpClient = getConnection();
+        CloseableHttpResponse response = null;
+        try {
+
+            StringEntity se = new StringEntity(jsonstr, Charset.forName("UTF-8"));
+            se.setContentType("text/json");
+            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
+            httpPost.setEntity(se);
+            response = httpClient.execute(httpPost);
+            int status = response.getStatusLine().getStatusCode();
+            logger.info("http request url : " + url + " status : " + status);
+            if (status >= 200 && status < 300) {
+                HttpEntity entity = response.getEntity();
+                if (entity != null) {
+                    result = EntityUtils.toString(response.getEntity(), "UTF-8");
+                    logger.info("Request result : " + result);
+                }
+            }
+            EntityUtils.consume(response.getEntity());
+            response.close();
+            return result;
+
+        } catch (IOException e) {
+            logger.error(e.getMessage(), e);
+        } finally {
+            httpPost.releaseConnection();
+            if (response != null) {
+                try {
+                    EntityUtils.consume(response.getEntity());
+                    response.close();
+                } catch (IOException e) {
+                    logger.error(e.getMessage(), e);
+                }
+            }
+        }
+        return result;
+    }
+
+    /**
+     * 发送 POST 请求(HTTP),K-V形式
+     *
+     * @param url    接口URL
+     * @param params 参数map
+     * @return
+     */
+    public String doPost(String url, Map<String, String> params) {
+        String result = null;
+        HttpPost httpPost = new HttpPost(url);
+        CloseableHttpClient httpClient = getConnection();
+        CloseableHttpResponse response = null;
+        try {
+            List<NameValuePair> pairList = new ArrayList<>(params.size());
+            for (Map.Entry<String, String> entry : params.entrySet()) {
+                NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
+                pairList.add(pair);
+            }
+            httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
+            response = httpClient.execute(httpPost);
+            int status = response.getStatusLine().getStatusCode();
+            logger.info("http request url : " + url + " status : " + status);
+            if (status >= 200 && status < 300) {
+                HttpEntity entity = response.getEntity();
+                if (entity != null) {
+                    result = EntityUtils.toString(response.getEntity(), "UTF-8");
+                    logger.info("Request result : " + result);
+                }
+            }
+            EntityUtils.consume(response.getEntity());
+            response.close();
+            return result;
+
+        } catch (IOException e) {
+            logger.error(e.getMessage(), e);
+        } finally {
+            httpPost.releaseConnection();
+            if (response != null) {
+                try {
+                    EntityUtils.consume(response.getEntity());
+                    response.close();
+                } catch (IOException e) {
+                    logger.error(e.getMessage(), e);
+                }
+            }
+        }
+        return result;
+    }
+    /**
+     * 发送 POST 请求(HTTP),K-V形式
+     *
+     * @param url    接口URL
+     * @param params 参数map
+     * @return
+     */
+    public String doPost(String url, Map<String, String> params, String token) {
+        String result = null;
+        HttpPost httpPost = new HttpPost(url);
+        CloseableHttpClient httpClient = getConnection();
+        CloseableHttpResponse response = null;
+        try {
+            List<NameValuePair> pairList = new ArrayList<>(params.size());
+            for (Map.Entry<String, String> entry : params.entrySet()) {
+                NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
+                pairList.add(pair);
+            }
+            httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
+            httpPost.addHeader("token", token);
+            response = httpClient.execute(httpPost);
+            int status = response.getStatusLine().getStatusCode();
+            logger.info("http request url : " + url + " status : " + status);
+            if (status >= 200 && status < 300) {
+                HttpEntity entity = response.getEntity();
+                if (entity != null) {
+                    result = EntityUtils.toString(response.getEntity(), "UTF-8");
+                    logger.info("Request result : " + result);
+                }
+            }
+            EntityUtils.consume(response.getEntity());
+            response.close();
+            return result;
+
+        } catch (IOException e) {
+            logger.error(e.getMessage(), e);
+        } finally {
+            httpPost.releaseConnection();
+            if (response != null) {
+                try {
+                    EntityUtils.consume(response.getEntity());
+                    response.close();
+                } catch (IOException e) {
+                    logger.error(e.getMessage(), e);
+                }
+            }
+        }
+        return result;
+    }
+
+}

+ 277 - 0
HttpUtil.java

@@ -0,0 +1,277 @@
+/**
+ * @Filename:HttpUtil.java
+ * @Author:caiqf
+ * @Date�?013-9-23
+ */
+package com.happy.Unitil_nsh;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.io.BufferedReader;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.ZipException;
+
+/**
+ * @Class:HttpsUtil.java
+ * @Description�?
+ * @Author:caiqf
+ * @Date�?013-9-23
+ */
+@SuppressWarnings("all")
+public class HttpUtil {
+    private static final Log log = LogFactory.getLog(HttpUtil.class);
+
+    /**
+     * HTTP协议GET请求方法
+     */
+    public static String httpMethodGet(String url, String gb) {
+        if (null == gb || "".equals(gb)) {
+            gb = "UTF-8";
+        }
+        StringBuffer sb = new StringBuffer();
+        URL urls;
+        HttpURLConnection uc = null;
+        BufferedReader in = null;
+        try {
+            urls = new URL(url);
+            uc = (HttpURLConnection) urls.openConnection();
+            uc.setRequestMethod("GET");
+            uc.connect();
+            in = new BufferedReader(new InputStreamReader(uc.getInputStream(), gb));
+            String readLine = "";
+            while ((readLine = in.readLine()) != null) {
+                sb.append(readLine);
+            }
+            if (in != null) {
+                in.close();
+            }
+            if (uc != null) {
+                uc.disconnect();
+            }
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            if (uc != null) {
+                uc.disconnect();
+            }
+        }
+        return sb.toString();
+    }
+
+    /**
+     * HTTP协议POST请求方法
+     */
+    public static String httpMethodPost(String url, String params, String gb) {
+        if (null == gb || "".equals(gb)) {
+            gb = "UTF-8";
+        }
+        StringBuffer sb = new StringBuffer();
+        URL urls;
+        HttpURLConnection uc = null;
+        BufferedReader in = null;
+        try {
+            urls = new URL(url);
+            uc = (HttpURLConnection) urls.openConnection();
+            uc.setRequestMethod("POST");
+            uc.setDoOutput(true);
+            uc.setDoInput(true);
+            uc.setUseCaches(false);
+            uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
+            uc.connect();
+            DataOutputStream out = new DataOutputStream(uc.getOutputStream());
+            out.write(params.getBytes(gb));
+            out.flush();
+            out.close();
+            in = new BufferedReader(new InputStreamReader(uc.getInputStream(), gb));
+            String readLine = "";
+            while ((readLine = in.readLine()) != null) {
+                sb.append(readLine);
+            }
+            if (in != null) {
+                in.close();
+            }
+            if (uc != null) {
+                uc.disconnect();
+            }
+        } catch (IOException e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            if (uc != null) {
+                uc.disconnect();
+            }
+        }
+        return sb.toString();
+    }
+
+    /**
+     * HTTP协议POST请求方法
+     */
+    public static String httpMethodPostJson(String url, String params, String gb) {
+        if (null == gb || "".equals(gb)) {
+            gb = "UTF-8";
+        }
+        StringBuffer sb = new StringBuffer();
+        URL urls;
+        HttpURLConnection uc = null;
+        BufferedReader in = null;
+        try {
+            urls = new URL(url);
+            uc = (HttpURLConnection) urls.openConnection();
+            uc.setRequestMethod("POST");
+            uc.setDoOutput(true);
+            uc.setDoInput(true);
+            uc.setUseCaches(false);
+            uc.setRequestProperty("Content-Type", "application/json");
+            uc.connect();
+            DataOutputStream out = new DataOutputStream(uc.getOutputStream());
+            out.write(params.getBytes(gb));
+            out.flush();
+            out.close();
+            in = new BufferedReader(new InputStreamReader(uc.getInputStream(), gb));
+            String readLine = "";
+            while ((readLine = in.readLine()) != null) {
+                sb.append(readLine);
+            }
+            if (in != null) {
+                in.close();
+            }
+            if (uc != null) {
+                uc.disconnect();
+            }
+        } catch (IOException e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            if (uc != null) {
+                uc.disconnect();
+            }
+        }
+        return sb.toString();
+    }
+
+
+    /**
+     * HTTP协议POST请求方法
+     */
+    public static String httpMethodPost(String url, TreeMap<String, String> paramsMap, String gb) {
+        if (null == gb || "".equals(gb)) {
+            gb = "UTF-8";
+        }
+        String params = null;
+        if (null != paramsMap) {
+            params = getParamStr(paramsMap);
+        }
+        System.out.println("====post请求参数= " + params);
+        StringBuffer sb = new StringBuffer();
+        URL urls;
+        HttpURLConnection uc = null;
+        BufferedReader in = null;
+        try {
+            urls = new URL(url);
+            uc = (HttpURLConnection) urls.openConnection();
+            uc.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
+            uc.setDoOutput(true);
+            uc.setDoInput(true);
+            uc.setRequestMethod("POST");
+            uc.setUseCaches(false);
+            uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
+            uc.connect();
+            DataOutputStream out = new DataOutputStream(uc.getOutputStream());
+            out.write(params.getBytes(gb));
+            out.flush();
+            out.close();
+            in = new BufferedReader(new InputStreamReader(uc.getInputStream(), gb));
+            String readLine = "";
+            while ((readLine = in.readLine()) != null) {
+                sb.append(readLine);
+            }
+            if (in != null) {
+                in.close();
+            }
+            if (uc != null) {
+                uc.disconnect();
+            }
+        } catch (IOException e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            if (uc != null) {
+                uc.disconnect();
+            }
+        }
+        return sb.toString();
+    }
+
+    public static String httpMethodPostGZIP(String url,
+                                            TreeMap<String, String> paramsMap, String gb) {
+        System.out.println("===url:" + url);
+        if (null == gb || "".equals(gb)) {
+            gb = "UTF-8";
+        }
+        String params = null;
+        if (null != paramsMap) {
+            params = getParamStr(paramsMap);
+        }
+
+        StringBuffer sb = new StringBuffer();
+        URL urls;
+        HttpURLConnection uc = null;
+        BufferedReader in = null;
+        try {
+            urls = new URL(url);
+            uc = (HttpURLConnection) urls.openConnection();
+            uc.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
+            uc.setDoOutput(true);
+            uc.setDoInput(true);
+            uc.setRequestMethod("POST");
+            uc.setUseCaches(false);
+            uc.connect();
+            DataOutputStream out = new DataOutputStream(uc.getOutputStream());
+            out.write(params.getBytes(gb));
+            out.flush();
+            out.close();
+            in = new BufferedReader(new InputStreamReader(new GZIPInputStream(uc.getInputStream()), gb));
+
+            String readLine = "";
+            while ((readLine = in.readLine()) != null) {
+                sb.append(readLine).append("\n");
+            }
+            if (in != null) {
+                in.close();
+            }
+            if (uc != null) {
+                uc.disconnect();
+            }
+        } catch (ZipException e) {
+            log.error("暂无数据");
+        } catch (IOException e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            if (uc != null) {
+                uc.disconnect();
+            }
+        }
+        return sb.toString();
+    }
+
+    /**
+     * HTTP协议POST请求添加参数的封装方�?
+     */
+    private static String getParamStr(TreeMap<String, String> paramsMap) {
+        StringBuilder param = new StringBuilder();
+        for (Iterator<Map.Entry<String, String>> it = paramsMap.entrySet().iterator(); it.hasNext(); ) {
+            Map.Entry<String, String> e = it.next();
+            param.append("&").append(URLEncoder.encode(e.getKey())).append("=").append(URLEncoder.encode(e.getValue()));
+        }
+        return param.toString().substring(1);
+    }
+
+}

+ 200 - 0
HttpUtils.java

@@ -0,0 +1,200 @@
+package com.happy.Until;
+
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+import org.apache.http.HttpEntity;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.util.EntityUtils;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+/**
+ * http post 提交 和 get请求
+ * 
+ * @author QT-666
+ * 
+ */
+public class HttpUtils {
+	private static RequestConfig requestConfig = RequestConfig.custom()
+			.setSocketTimeout(15000).setConnectTimeout(15000)
+			.setConnectionRequestTimeout(15000).build();
+
+	public static String get(String url, Map<String, String> params) {
+		CloseableHttpClient httpClient = null;
+		HttpGet httpGet = null;
+		String re = "";
+		try {
+			httpClient = HttpClients.createDefault();
+			RequestConfig requestConfig = RequestConfig.custom()
+					.setSocketTimeout(20000).setConnectTimeout(20000).build();
+			String ps = "";
+			for (String pKey : params.keySet()) {
+				if (!"".equals(ps)) {
+					ps = ps + "&";
+				}
+				ps = pKey + "=" + params.get(pKey);
+			}
+			if (!"".equals(ps)) {
+				url = url + "?" + ps;
+			}
+			httpGet = new HttpGet(url);
+			httpGet.setConfig(requestConfig);
+			CloseableHttpResponse response = httpClient.execute(httpGet);
+			HttpEntity httpEntity = response.getEntity();
+			re = EntityUtils.toString(httpEntity, "utf-8");
+		} catch (ClientProtocolException e) {
+			e.printStackTrace();
+		} catch (IOException e) {
+			e.printStackTrace();
+		} finally {
+			try {
+				if (httpGet != null) {
+					httpGet.releaseConnection();
+				}
+				if (httpClient != null) {
+					httpClient.close();
+				}
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+		return re;
+	}
+
+	/**
+	 * 发送http post请求
+	 * 
+	 * @param
+	 *
+	 * @param
+	 *
+	 */
+	public static String post(String url, Map<String, String> params) throws IOException {
+		CloseableHttpClient httpClient = null;
+		HttpPost httpPost = null;
+		String re = "";
+		try {
+			httpClient = HttpClients.createDefault();
+			RequestConfig requestConfig = RequestConfig.custom()
+					.setSocketTimeout(20000).setConnectTimeout(20000).build();
+			httpPost = new HttpPost(url);
+			httpPost.setConfig(requestConfig);
+			List<NameValuePair> ps = new ArrayList<NameValuePair>();
+			for (String pKey : params.keySet()) {
+				ps.add(new BasicNameValuePair(pKey, params.get(pKey)));
+			}
+			httpPost.setEntity(new UrlEncodedFormEntity(ps));
+			CloseableHttpResponse response = httpClient.execute(httpPost);
+			HttpEntity httpEntity = response.getEntity();
+			re = EntityUtils.toString(httpEntity, "utf-8");
+		} catch (ClientProtocolException e) {
+			e.printStackTrace();
+		} catch (IOException e) {
+			e.printStackTrace();
+		} finally {
+			try {
+				if (httpPost != null) {
+					httpPost.releaseConnection();
+				}
+				if (httpClient != null) {
+					httpClient.close();
+				}
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+		return re;
+	}
+
+	/**
+	 * 发送post请求Https,参数是字符串
+	 *
+	 * @param httpPost
+	 * @return
+	 */
+	public static String post(String url, String body) throws Exception {
+		String str = "";
+		CloseableHttpClient httpClient = null;
+		HttpPost httpPost = null;
+		try {
+			httpClient = HttpClients.createDefault();
+			RequestConfig requestConfig = RequestConfig.custom()
+					.setSocketTimeout(20000).setConnectTimeout(20000).build();
+			httpPost = new HttpPost(url);
+			httpPost.setConfig(requestConfig);
+			httpPost.setEntity(new StringEntity(body, "utf-8"));
+			CloseableHttpResponse response = httpClient.execute(httpPost);
+			HttpEntity httpEntity = response.getEntity();
+			str = EntityUtils.toString(httpEntity, "utf-8");
+
+		} catch (ClientProtocolException e) {
+			e.printStackTrace();
+		} catch (IOException e) {
+			e.printStackTrace();
+		} finally {
+			try {
+				if (httpPost != null) {
+					httpPost.releaseConnection();
+				}
+				if (httpClient != null) {
+					httpClient.close();
+				}
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+		return new String(str.getBytes("iso-8859-1"));
+	}
+
+
+
+	public static String get(String strURL) throws Exception {
+		URL url = new URL(strURL);
+		HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
+		httpConn.setRequestMethod("GET");
+		httpConn.connect();
+
+		BufferedReader reader = new BufferedReader(new InputStreamReader(
+				httpConn.getInputStream(), "utf-8"));
+		String line;
+		StringBuffer buffer = new StringBuffer();
+		while ((line = reader.readLine()) != null) {
+			buffer.append(line);
+		}
+		reader.close();
+		httpConn.disconnect();
+
+		return buffer.toString();
+	}
+
+	public static void main(String[] args) throws Exception {
+		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
+		String time = df.format(new Date());
+		Map<String, String> req = new HashMap<>();
+		req.put("operator_id", "000000002");
+		req.put("operator_secret", "SBC88d0ItR3w6oCTY");
+		req.put("data_secret", "Epc3hhs0imtVhPSu");
+		req.put("data_secret_iv", "r57m1sr8Tg2E302L");
+		req.put("sign_key", "ikAhygeGCRnEdhjgBKf");
+		req.put("timeStamp", time);
+		req.put("seq", "0001");
+		String msg = post("http://183.129.139.222:10022/ems-share-api/queryToken", req);
+		System.out.println("aaa: "+msg);
+	}
+}

+ 487 - 0
HttpsClient.java

@@ -0,0 +1,487 @@
+package com.happy.common.http;
+
+import com.alibaba.fastjson.JSONObject;
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+import com.happy.Until.CreateSign1;
+import com.happy.Until.TimeExchange;
+import com.happy.common.wx.WxConfig;
+import com.happy.common.wx.WxConstants;
+import com.happy.common.wx.WxUtil;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.HttpEntity;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.util.EntityUtils;
+
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import java.io.*;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLConnection;
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+/**
+ * HttpsClient类
+ * @author lujunjie
+ * @date   2018/03/01
+ */
+public class HttpsClient {
+
+    /**
+     * GET请求方式
+     */
+    public static final String METHOD_GET = "GET";
+    /**
+     * POST请求方式
+     */
+    public static final String METHOD_POST = "POST";
+    /**
+     * 连接超时时间
+     */
+    private static Integer CONNECTION_TIMEOUT = WxConfig.connectionTimeout;
+    /**
+     * 请求超时时间
+     */
+    private static Integer READ_TIMEOUT = WxConfig.readTimeout;
+
+    /**
+     * 发起https请求
+     * @param requestUrl 请求地址
+     * @param requestMethod 请求方式(Get或者post)
+     * @param postData 提交数据
+     * @return JSONObject
+     */
+    public static JSONObject httpsRequestReturnJSONObject(String requestUrl, String requestMethod, String postData) throws Exception{
+        JSONObject  jsonObject = JSONObject.parseObject(HttpsClient.httpsRequestReturnString(requestUrl,requestMethod,postData));
+        System.out.println("jsonObjectDate:  " + jsonObject);
+        return jsonObject;
+    }
+
+
+    /**
+     * 发起https请求
+     * @param requestUrl 请求地址
+     * @param requestMethod 请求方式(Get或者post)
+     * @param postData 提交数据
+     * @return String
+     */
+    public static String httpsRequestReturnString(String requestUrl, String requestMethod, String postData) throws Exception{
+        String response;
+        HttpsURLConnection httpsUrlConnection = null;
+        try{
+            //创建https请求证书
+            TrustManager[] tm={new MyX509TrustManager()};
+            //创建SSLContext管理器对像,使用我们指定的信任管理器初始化
+            SSLContext sslContext=SSLContext.getInstance("SSL","SunJSSE");
+            sslContext.init(null, tm, new java.security.SecureRandom());
+            SSLSocketFactory ssf=sslContext.getSocketFactory();
+
+            // 创建URL对象
+            URL url= new URL(requestUrl);
+            // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
+            httpsUrlConnection=(HttpsURLConnection)url.openConnection();
+            //设置ssl证书
+            httpsUrlConnection.setSSLSocketFactory(ssf);
+
+            //设置header信息
+            httpsUrlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
+            //设置User-Agent信息
+            httpsUrlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
+            //设置可接受信息
+            httpsUrlConnection.setDoOutput(true);
+            //设置可输入信息
+            httpsUrlConnection.setDoInput(true);
+            //不使用缓存
+            httpsUrlConnection.setUseCaches(false);
+            //设置请求方式(GET/POST)
+            httpsUrlConnection.setRequestMethod(requestMethod);
+            //设置连接超时时间
+            if (CONNECTION_TIMEOUT > 0) {
+                httpsUrlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
+            } else {
+                //默认10秒超时
+                httpsUrlConnection.setConnectTimeout(10000);
+            }
+            //设置请求超时
+            if (READ_TIMEOUT > 0) {
+                httpsUrlConnection.setReadTimeout(READ_TIMEOUT);
+            } else {
+                //默认10秒超时
+                httpsUrlConnection.setReadTimeout(10000);
+            }
+            //设置编码
+            httpsUrlConnection.setRequestProperty("Charsert", WxConstants.DEFAULT_CHARSET);
+
+            //判断是否需要提交数据
+            if(StringUtils.equals(requestMethod,HttpsClient.METHOD_POST) && StringUtils.isNotBlank(postData)){
+                //讲参数转换为字节提交
+                byte[] bytes = postData.getBytes(WxConstants.DEFAULT_CHARSET);
+                //设置头信息
+                httpsUrlConnection.setRequestProperty("Content-Length", Integer.toString(bytes.length));
+                //开始连接
+                httpsUrlConnection.connect();
+                //防止中文乱码
+                OutputStream outputStream=httpsUrlConnection.getOutputStream();
+                outputStream.write(postData.getBytes(WxConstants.DEFAULT_CHARSET));
+                outputStream.flush();
+                outputStream.close();
+            }else{
+                //开始连接
+                httpsUrlConnection.connect();
+            }
+            response = WxUtil.getStreamString(httpsUrlConnection.getInputStream());
+        }catch (Exception e){
+            throw new Exception();
+        }finally {
+            if (httpsUrlConnection != null) {
+                // 关闭连接
+                httpsUrlConnection.disconnect();
+            }
+        }
+        return response;
+    }
+
+
+    public static void get(String url, Map<String, String> params){
+        CloseableHttpClient httpClient = null;
+        HttpGet httpGet = null;
+        try {
+            httpClient = HttpClients.createDefault();
+            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
+            String ps = "";
+            for (String pKey : params.keySet()) {
+                if(!"".equals(ps)){
+                    ps = ps + "&";
+                }
+                ps = pKey+"="+params.get(pKey);
+            }
+            if(!"".equals(ps)){
+                url = url + "?" + ps;
+            }
+            httpGet = new HttpGet(url);
+            httpGet.setConfig(requestConfig);
+            CloseableHttpResponse response = httpClient.execute(httpGet);
+            HttpEntity httpEntity = response.getEntity();
+            System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
+        } catch (ClientProtocolException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }finally{
+            try {
+                if(httpGet!=null){
+                    httpGet.releaseConnection();
+                }
+                if(httpClient!=null){
+                    httpClient.close();
+                }
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+    }
+
+    public static String get(String strURL) throws Exception{
+
+        URL url = new URL(strURL);
+        HttpURLConnection httpConn = (HttpURLConnection)
+                url.openConnection();
+        httpConn.setRequestMethod("GET");
+        httpConn.connect();
+        System.out.println("bbb: "+httpConn.getResponseCode());
+        BufferedReader reader = new BufferedReader(new InputStreamReader(
+                httpConn.getInputStream(),"utf-8"));
+        String line;
+        StringBuffer buffer = new StringBuffer();
+        while ((line = reader.readLine()) != null) {
+            buffer.append(line);
+        }
+        reader.close();
+        httpConn.disconnect();
+
+        return buffer.toString();
+    }
+
+    /**
+     * 发送 post请求
+     * @param
+     * @param
+     */
+    public static void post(String url, Map<String, String> params){
+        CloseableHttpClient httpClient = null;
+        HttpPost httpPost = null;
+        try {
+            httpClient = HttpClients.createDefault();
+            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
+            httpPost = new HttpPost(url);
+            httpPost.setConfig(requestConfig);
+            List<NameValuePair> ps = new ArrayList<NameValuePair>();
+            for (String pKey : params.keySet()) {
+                ps.add(new BasicNameValuePair(pKey, params.get(pKey)));
+            }
+            httpPost.setEntity(new UrlEncodedFormEntity(ps));
+            CloseableHttpResponse response = httpClient.execute(httpPost);
+            HttpEntity httpEntity = response.getEntity();
+            System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
+        } catch (ClientProtocolException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }finally{
+            try {
+                if(httpPost!=null){
+                    httpPost.releaseConnection();
+                }
+                if(httpClient!=null){
+                    httpClient.close();
+                }
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+    }
+
+    //url表示请求链接,param表示json格式的请求参数		//自定义菜单创建访问方式
+    public static String sendPost(String url, String param) {
+        PrintWriter out = null;
+        BufferedReader in = null;
+        String result = "";
+        try {
+            URL realUrl = new URL(url);
+            // 打开和URL之间的连接
+            URLConnection conn = realUrl.openConnection();
+            // 设置通用的请求属性 注意Authorization生成
+            // conn.setRequestProperty("Content-Type",
+            // "application/x-www-form-urlencoded");
+            // 发送POST请求必须设置如下两行
+            conn.setDoOutput(true);
+            conn.setDoInput(true);
+            // 获取URLConnection对象对应的输出流
+            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
+            // 发送请求参数
+            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;
+            }
+        } catch (Exception e) {
+            System.out.println("发送 请求出现异常!" + e);
+            e.printStackTrace();
+        }
+        // 使用finally块来关闭输出流、输入流
+        finally {
+            try {
+                if (out != null) {
+                    out.close();
+                }
+                if (in != null) {
+                    in.close();
+                }
+            } catch (IOException ex) {
+                ex.printStackTrace();
+            }
+        }
+        return result;
+    }
+
+
+    //url表示请求链接,param表示json格式的请求参数		//自定义菜单创建访问方式
+    public static String sendPost2(String url, String param) {
+        PrintWriter out = null;
+        BufferedReader in = null;
+        String result = "";
+        try {
+            HttpsURLConnection httpsUrlConnection = null;
+            //创建https请求证书
+            TrustManager[] tm={new MyX509TrustManager()};
+            //创建SSLContext管理器对像,使用我们指定的信任管理器初始化
+            SSLContext sslContext=SSLContext.getInstance("SSL","SunJSSE");
+            sslContext.init(null, tm, new java.security.SecureRandom());
+            SSLSocketFactory ssf=sslContext.getSocketFactory();
+            // 创建URL对象
+            URL realUrl= new URL(url);
+            // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象,
+            // 打开和URL之间的连接
+            httpsUrlConnection=(HttpsURLConnection)realUrl.openConnection();
+            //设置ssl证书
+            httpsUrlConnection.setSSLSocketFactory(ssf);
+            // 设置通用的请求属性 注意Authorization生成
+            // conn.setRequestProperty("Content-Type",
+            // "application/x-www-form-urlencoded");
+            // 发送POST请求必须设置如下两行
+            httpsUrlConnection.setRequestMethod("POST");
+            httpsUrlConnection.setDoOutput(true);
+            httpsUrlConnection.setDoInput(true);
+            // 获取URLConnection对象对应的输出流
+            out = new PrintWriter(new OutputStreamWriter(httpsUrlConnection.getOutputStream(),"utf-8"));
+            // 发送请求参数
+            out.print("&"+param);
+            // flush输出流的缓冲
+            out.flush();
+            if (httpsUrlConnection.getResponseCode()==200) {
+                // 定义BufferedReader输入流来读取URL的响应
+                in = new BufferedReader(
+                        new InputStreamReader(httpsUrlConnection.getInputStream(), "utf-8"));
+                String line;
+                while ((line = in.readLine()) != null) {
+                    result += line;
+                }
+            }else {
+                result = "获取输入流异常!";
+            }
+        } catch (Exception e) {
+            System.out.println("发送 请求出现异常!" + e);
+            e.printStackTrace();
+        }
+        // 使用finally块来关闭输出流、输入流
+        finally {
+            try {
+                if (out != null) {
+                    out.close();
+                }
+                if (in != null) {
+                    in.close();
+                }
+            } catch (IOException ex) {
+                ex.printStackTrace();
+            }
+        }
+        return result;
+    }
+
+    public static String dateToStamp(String s) throws Exception {
+        String res = "";
+        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        Date date = simpleDateFormat.parse(s);
+        long time = date.getTime();
+        res = String.valueOf(time);
+        return res;
+    }
+
+    /*
+     * 将时间戳转换为时间
+     */
+    public static String stampToDate(String s){
+        String res;
+        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        long lt = new Long(s);
+        Date date = new Date(lt);
+        res = simpleDateFormat.format(date);
+        return res;
+    }
+
+    public static String sendJson(String request_url, JSONObject json) {
+        OutputStreamWriter out = null;
+        InputStream is = null;
+        String result = "";
+        try {
+            URL url = new URL(request_url);// 创建连接
+            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+            connection.setDoOutput(true);
+            connection.setDoInput(true);
+            connection.setUseCaches(false);
+            connection.setInstanceFollowRedirects(true);
+            connection.setRequestMethod("POST"); // 设置请求方式
+            // 设置接收数据的格式
+            connection.setRequestProperty("Accept", "application/json");
+            // 设置发送数据的格式
+            connection.setRequestProperty("Content-Type", "application/json");
+            connection.connect();
+            out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
+            out.append(json.toString());
+            out.flush();
+            out.close();
+            // 读取响应
+            is = connection.getInputStream();
+            int length = (int) connection.getContentLength();// 获取字节长度
+            System.out.println(length);
+            if (length != -1) {
+                byte[] data = new byte[length];
+                byte[] temp = new byte[512];
+                int readLen = 0;
+                int destPos = 0;
+                while ((readLen = is.read(temp)) > 0) {
+                    System.arraycopy(temp, 0, data, destPos, readLen);
+                    destPos += readLen;
+                }
+                result = new String(data, "UTF-8"); // utf-8编码
+            }
+        } catch (IOException e) {
+            e.printStackTrace();
+        } finally {
+            try {
+                is.close();
+                out.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+        return result;
+    }
+
+    public static String sendJson2(String request_url, JSONObject json) {
+        OutputStreamWriter out = null;
+        InputStream is = null;
+        String result = "";
+        try {
+            URL url = new URL(request_url);// 创建连接
+            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+            connection.setDoOutput(true);
+            connection.setDoInput(true);
+            connection.setUseCaches(false);
+            connection.setInstanceFollowRedirects(true);
+            connection.setRequestMethod("POST"); // 设置请求方式
+            // 设置接收数据的格式
+            connection.setRequestProperty("Accept", "application/json");
+            // 设置发送数据的格式
+            connection.setRequestProperty("Content-Type", "application/json");
+            connection.connect();
+            out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
+            out.append(json.toString());
+            out.flush();
+            out.close();
+            // 读取响应
+            is = connection.getInputStream();
+            BufferedReader in = new BufferedReader(new InputStreamReader(is));
+            result = in.readLine();
+        } catch (IOException e) {
+            e.printStackTrace();
+        } finally {
+            try {
+                is.close();
+                out.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+        return result;
+    }
+
+    public static void main(String[] args) throws Exception {
+        JSONObject json = new JSONObject();
+        json.put("buildCode", "5栋");
+        json.put("currentAggr", "20");
+        json.put("energyType", "2");
+        json.put("updateTime", "2021-09-09 10:15:33");
+        String msg = sendJson2("https://chtech.ncjti.edu.cn/bigdata-api/api/energy/energyDataUpload", json);
+        System.out.println(msg);
+    }
+}

+ 390 - 0
HttpsUtil.java

@@ -0,0 +1,390 @@
+/**
+ * @Filename:HttpsUtil.java
+ * @Author:caiqf
+ * @Date�?013-9-23
+ */
+package com.happy.Unitil_nsh;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.net.ssl.*;
+import java.io.*;
+import java.net.URL;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.zip.GZIPInputStream;
+
+/**
+ * @Class:HttpsUtil.java
+ * @Description�?
+ * @Author:caiqf
+ * @Date�?013-9-23
+ */
+public class HttpsUtil {
+    private static final Log log = LogFactory.getLog(HttpsUtil.class);
+
+    private static class MyTrustManager implements X509TrustManager {
+        public void checkClientTrusted(X509Certificate[] chain, String authType)
+                throws CertificateException {
+        }
+
+        public void checkServerTrusted(X509Certificate[] chain, String authType)
+                throws CertificateException {
+        }
+
+        public X509Certificate[] getAcceptedIssuers() {
+            return new X509Certificate[]{};
+        }
+    }
+
+    private static class MyHostnameVerifier implements HostnameVerifier {
+        public boolean verify(String hostname, SSLSession session) {
+            return true;
+        }
+    }
+
+    /**
+     * HTTP协议GET请求方法
+     */
+    public static String httpMethodGet(String url, String gb) {
+        if (null == gb || "".equals(gb)) {
+            gb = "UTF-8";
+        }
+        StringBuffer sb = new StringBuffer();
+        URL urls;
+        HttpsURLConnection uc = null;
+        BufferedReader in = null;
+        try {
+            SSLContext sc = SSLContext.getInstance("SSL");
+            sc.init(null, new TrustManager[]{new MyTrustManager()}, new java.security.SecureRandom());
+            urls = new URL(url);
+            uc = (HttpsURLConnection) urls.openConnection();
+            uc.setSSLSocketFactory(sc.getSocketFactory());
+            uc.setHostnameVerifier(new MyHostnameVerifier());
+            uc.setRequestMethod("GET");
+            uc.connect();
+            in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8"));
+            String readLine = "";
+            while ((readLine = in.readLine()) != null) {
+                sb.append(readLine);
+            }
+            if (in != null) {
+                in.close();
+            }
+            if (uc != null) {
+                uc.disconnect();
+            }
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            if (uc != null) {
+                uc.disconnect();
+            }
+        }
+        return sb.toString();
+    }
+
+    /**
+     * HTTP协议GET请求方法
+     */
+    public static byte[] httpMethodGetFile(String url) {
+        byte[] btFile = null;
+        URL urls = null;
+        HttpsURLConnection uc = null;
+        try {
+            SSLContext sc = SSLContext.getInstance("SSL");
+            sc.init(null, new TrustManager[]{new MyTrustManager()},
+                    new java.security.SecureRandom());
+            urls = new URL(url);
+            uc = (HttpsURLConnection) urls.openConnection();
+            uc.setSSLSocketFactory(sc.getSocketFactory());
+            uc.setHostnameVerifier(new MyHostnameVerifier());
+            uc.setRequestMethod("GET");
+            uc.connect();
+            InputStream inStream = uc.getInputStream(); // 获取文件流二进制数据
+            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
+            byte[] buffer = new byte[1024];
+            int len = 0;
+            while ((len = inStream.read(buffer)) != -1) {
+                outStream.write(buffer, 0, len);
+            }
+            inStream.close();
+            btFile = outStream.toByteArray();
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            if (uc != null) {
+                uc.disconnect();
+            }
+        }
+        return btFile;
+    }
+
+    /**
+     * HTTP协议POST请求方法
+     */
+    public static String httpMethodPost(String url, String params, String gb) {
+        if (null == gb || "".equals(gb)) {
+            gb = "UTF-8";
+        }
+        StringBuffer sb = new StringBuffer();
+        URL urls;
+        HttpsURLConnection uc = null;
+        BufferedReader in = null;
+        try {
+            SSLContext sc = SSLContext.getInstance("SSL");
+            sc.init(null, new TrustManager[]{new MyTrustManager()}, new java.security.SecureRandom());
+            urls = new URL(url);
+            uc = (HttpsURLConnection) urls.openConnection();
+            uc.setSSLSocketFactory(sc.getSocketFactory());
+            uc.setHostnameVerifier(new MyHostnameVerifier());
+            uc.setRequestMethod("POST");
+            uc.setDoOutput(true);
+            uc.setDoInput(true);
+            uc.setUseCaches(false);
+            uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
+            uc.connect();
+            DataOutputStream out = new DataOutputStream(uc.getOutputStream());
+            out.write(params.getBytes(gb));
+            out.flush();
+            out.close();
+            in = new BufferedReader(new InputStreamReader(uc.getInputStream(), gb));
+            String readLine = "";
+            while ((readLine = in.readLine()) != null) {
+                sb.append(readLine);
+            }
+            if (in != null) {
+                in.close();
+            }
+            if (uc != null) {
+                uc.disconnect();
+            }
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            if (uc != null) {
+                uc.disconnect();
+            }
+        }
+        return sb.toString();
+    }
+
+    /**
+     * HTTP协议POST请求方法
+     */
+    public static byte[] httpMethodPostFile(String url, String params, String gb) {
+        if (null == gb || "".equals(gb)) {
+            gb = "UTF-8";
+        }
+        byte[] btFile = null;
+        URL urls = null;
+        HttpsURLConnection uc = null;
+        try {
+            SSLContext sc = SSLContext.getInstance("SSL");
+            sc.init(null, new TrustManager[]{new MyTrustManager()}, new java.security.SecureRandom());
+            urls = new URL(url);
+            uc = (HttpsURLConnection) urls.openConnection();
+            uc.setSSLSocketFactory(sc.getSocketFactory());
+            uc.setHostnameVerifier(new MyHostnameVerifier());
+            uc.setRequestMethod("POST");
+            uc.setDoOutput(true);
+            uc.setDoInput(true);
+            uc.setUseCaches(false);
+            uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
+            uc.connect();
+            DataOutputStream out = new DataOutputStream(uc.getOutputStream());
+            out.write(params.getBytes(gb));
+            out.flush();
+            out.close();
+            InputStream inStream = uc.getInputStream(); // 获取文件流二进制数据
+            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
+            byte[] buffer = new byte[1024];
+            int len = 0;
+            while ((len = inStream.read(buffer)) != -1) {
+                outStream.write(buffer, 0, len);
+            }
+            inStream.close();
+            btFile = outStream.toByteArray();
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            if (uc != null) {
+                uc.disconnect();
+            }
+        }
+        return btFile;
+    }
+
+    /**
+     * HTTP协议POST请求方法
+     */
+    public static String httpMethodPost(String url, TreeMap<String, String> paramsMap, String gb) {
+        if (null == gb || "".equals(gb)) {
+            gb = "UTF-8";
+        }
+        String params = null;
+        if (null != paramsMap) {
+            params = getParamStr(paramsMap);
+        }
+        System.out.println("====post请求参数= " + params);
+        StringBuffer sb = new StringBuffer();
+        URL urls;
+        HttpsURLConnection uc = null;
+        BufferedReader in = null;
+        try {
+            SSLContext sc = SSLContext.getInstance("SSL");
+            sc.init(null, new TrustManager[]{new MyTrustManager()}, new java.security.SecureRandom());
+            urls = new URL(url);
+            uc = (HttpsURLConnection) urls.openConnection();
+            uc.setSSLSocketFactory(sc.getSocketFactory());
+            uc.setHostnameVerifier(new MyHostnameVerifier());
+            uc.setRequestMethod("POST");
+            uc.setDoOutput(true);
+            uc.setDoInput(true);
+            uc.setUseCaches(false);
+            uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
+            uc.connect();
+            DataOutputStream out = new DataOutputStream(uc.getOutputStream());
+            out.write(params.getBytes(gb));
+            out.flush();
+            out.close();
+            in = new BufferedReader(new InputStreamReader(uc.getInputStream(), gb));
+            String readLine = "";
+            while ((readLine = in.readLine()) != null) {
+                sb.append(readLine);
+            }
+            if (in != null) {
+                in.close();
+            }
+            if (uc != null) {
+                uc.disconnect();
+            }
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            if (uc != null) {
+                uc.disconnect();
+            }
+        }
+        return sb.toString();
+    }
+
+    public static String httpMethodPostGZIP(String url, TreeMap<String, String> paramsMap, String gb) {
+        if (null == gb || "".equals(gb)) {
+            gb = "UTF-8";
+        }
+        String params = null;
+        if (null != paramsMap) {
+            params = getParamStr(paramsMap);
+        }
+        System.out.println("==================post请求地址:" + url);
+        System.out.println("==================post请求参数:" + params);
+        StringBuffer sb = new StringBuffer();
+        URL urls;
+        HttpsURLConnection uc = null;
+        BufferedReader in = null;
+        try {
+            SSLContext sc = SSLContext.getInstance("SSL");
+            sc.init(null, new TrustManager[]{new MyTrustManager()}, new java.security.SecureRandom());
+            urls = new URL(url);
+            uc = (HttpsURLConnection) urls.openConnection();
+            uc.setSSLSocketFactory(sc.getSocketFactory());
+            uc.setHostnameVerifier(new MyHostnameVerifier());
+            uc.setRequestMethod("POST");
+            uc.setDoOutput(true);
+            uc.setDoInput(true);
+            uc.setUseCaches(false);
+            uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
+            uc.connect();
+            DataOutputStream out = new DataOutputStream(uc.getOutputStream());
+            out.write(params.getBytes(gb));
+            out.flush();
+            out.close();
+            in = new BufferedReader(new InputStreamReader(new GZIPInputStream(uc.getInputStream()), gb));
+            String readLine = "";
+            while ((readLine = in.readLine()) != null) {
+                sb.append(readLine).append("\n");
+            }
+            if (in != null) {
+                in.close();
+            }
+            if (uc != null) {
+                uc.disconnect();
+            }
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            if (uc != null) {
+                uc.disconnect();
+            }
+        }
+        return sb.toString();
+    }
+
+    /**
+     * HTTP协议POST请求方法
+     */
+    public static byte[] httpMethodPostFile(String url, TreeMap<String, String> paramsMap, String gb) {
+        if (null == gb || "".equals(gb)) {
+            gb = "UTF-8";
+        }
+        String params = null;
+        if (null != paramsMap) {
+            params = getParamStr(paramsMap);
+        }
+
+        byte[] btFile = null;
+        URL urls = null;
+        HttpsURLConnection uc = null;
+        try {
+            SSLContext sc = SSLContext.getInstance("SSL");
+            sc.init(null, new TrustManager[]{new MyTrustManager()}, new java.security.SecureRandom());
+            urls = new URL(url);
+            uc = (HttpsURLConnection) urls.openConnection();
+            uc.setSSLSocketFactory(sc.getSocketFactory());
+            uc.setHostnameVerifier(new MyHostnameVerifier());
+            uc.setRequestMethod("POST");
+            uc.setDoOutput(true);
+            uc.setDoInput(true);
+            uc.setUseCaches(false);
+            uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
+            uc.connect();
+            DataOutputStream out = new DataOutputStream(uc.getOutputStream());
+            out.write(params.getBytes(gb));
+            out.flush();
+            out.close();
+            InputStream inStream = uc.getInputStream(); // 获取文件流二进制数据
+            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
+            byte[] buffer = new byte[1024];
+            int len = 0;
+            while ((len = inStream.read(buffer)) != -1) {
+                outStream.write(buffer, 0, len);
+            }
+            inStream.close();
+            btFile = outStream.toByteArray();
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            if (uc != null) {
+                uc.disconnect();
+            }
+        }
+        return btFile;
+    }
+
+    /**
+     * HTTP协议POST请求添加参数的封装方�?
+     */
+    private static String getParamStr(TreeMap<String, String> paramsMap) {
+        StringBuilder param = new StringBuilder();
+        for (Iterator<Map.Entry<String, String>> it = paramsMap.entrySet().iterator(); it.hasNext(); ) {
+            Map.Entry<String, String> e = it.next();
+            param.append("&").append(e.getKey()).append("=").append(e.getValue());
+        }
+        return param.toString().substring(1);
+    }
+}

+ 23 - 0
InterceptorConfig.java

@@ -0,0 +1,23 @@
+package com.happy.config;
+
+import com.happy.interceptor.AuthenticationInterceptor;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+/**
+ * @author yp
+ */
+@Configuration
+public class InterceptorConfig implements WebMvcConfigurer {
+    @Override
+    public void addInterceptors(InterceptorRegistry registry) {
+        registry.addInterceptor(authenticationInterceptor())
+                .addPathPatterns("/**");    // 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录
+    }
+    @Bean
+    public AuthenticationInterceptor authenticationInterceptor() {
+        return new AuthenticationInterceptor();
+    }
+}

+ 164 - 0
JaxbUtil.java

@@ -0,0 +1,164 @@
+package com.happy.Until.weixin;
+
+import org.apache.commons.lang.StringUtils;
+
+import javax.xml.bind.*;
+import javax.xml.bind.annotation.XmlAnyElement;
+import javax.xml.namespace.QName;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+/** 
+ * 使用Jaxb2.0实现XML<->Java Object的Binder. 
+ *  
+ * 特别支持Root对象是List的情形. 
+ *  
+ * @author 
+ */  
+public class JaxbUtil {  
+    // 多线程安全的Context.  
+    private JAXBContext jaxbContext;  
+  
+    /** 
+     * @param types 
+     *            所有需要序列化的Root对象的类型. 
+     */  
+    public JaxbUtil(Class<?>... types) {  
+        try {  
+            jaxbContext = JAXBContext.newInstance(types);  
+        } catch (JAXBException e) {  
+            throw new RuntimeException(e);  
+        }  
+    }  
+  
+    /** 
+     * Java Object->Xml. 
+     */  
+    public String toXml(Object root, String encoding) {  
+        try {  
+            StringWriter writer = new StringWriter();  
+            createMarshaller(encoding).marshal(root, writer);  
+            return writer.toString();  
+        } catch (JAXBException e) {  
+            throw new RuntimeException(e);  
+        }  
+    }  
+  
+    /** 
+     * Java Object->Xml, 特别支持对Root Element是Collection的情形. 
+     */  
+    @SuppressWarnings("unchecked")  
+    public String toXml(Collection root, String rootName, String encoding) {  
+        try {  
+            CollectionWrapper wrapper = new CollectionWrapper();  
+            wrapper.collection = root;  
+  
+            JAXBElement<CollectionWrapper> wrapperElement = new JAXBElement<CollectionWrapper>(  
+                    new QName(rootName), CollectionWrapper.class, wrapper);  
+  
+            StringWriter writer = new StringWriter();  
+            createMarshaller(encoding).marshal(wrapperElement, writer);  
+  
+            return writer.toString();  
+        } catch (JAXBException e) {  
+            throw new RuntimeException(e);  
+        }  
+    }  
+  
+    /** 
+     * Xml->Java Object. 
+     */  
+    @SuppressWarnings("unchecked")  
+    public <T> T fromXml(String xml) {  
+        try {  
+            StringReader reader = new StringReader(xml);  
+            return (T) createUnmarshaller().unmarshal(reader);  
+        } catch (JAXBException e) {  
+            throw new RuntimeException(e);  
+        }  
+    }  
+  
+    /** 
+     * Xml->Java Object, 支持大小写敏感或不敏感. 
+     */  
+    @SuppressWarnings("unchecked")  
+    public <T> T fromXml(String xml, boolean caseSensitive) {  
+        try {  
+            String fromXml = xml;  
+            if (!caseSensitive)  
+                fromXml = xml.toLowerCase();  
+            StringReader reader = new StringReader(fromXml);  
+            return (T) createUnmarshaller().unmarshal(reader);  
+        } catch (JAXBException e) {  
+            throw new RuntimeException(e);  
+        }  
+    }  
+  
+    /** 
+     * 创建Marshaller, 设定encoding(可为Null). 
+     */  
+    public Marshaller createMarshaller(String encoding) {  
+        try {  
+            Marshaller marshaller = jaxbContext.createMarshaller();  
+  
+            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);  
+  
+            if (StringUtils.isNotBlank(encoding)) {  
+                marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);  
+            }  
+            return marshaller;  
+        } catch (JAXBException e) {  
+            throw new RuntimeException(e);  
+        }  
+    }  
+  
+    /** 
+     * 创建UnMarshaller. 
+     */  
+    public Unmarshaller createUnmarshaller() {  
+        try {  
+            return jaxbContext.createUnmarshaller();  
+        } catch (JAXBException e) {  
+            throw new RuntimeException(e);  
+        }  
+    }  
+  
+    /** 
+     * 封装Root Element 是 Collection的情况. 
+     */  
+    public static class CollectionWrapper {  
+        @SuppressWarnings("unchecked")  
+        @XmlAnyElement  
+        protected Collection collection;  
+    }
+    /**
+     * 把map转换成xml格式
+     * @param params
+     * @return
+     * @throws Exception
+     */
+    public static String getRequestXml(Map<String, String> params) throws Exception{
+        StringBuffer sb = new StringBuffer();
+        sb.append("<xml>");
+        Set<Entry<String, String>> es = params.entrySet();
+        Iterator<Entry<String, String>> it = es.iterator();
+        while (it.hasNext()) {
+            Entry<String, String> entry = (Entry<String, String>) it
+                    .next();
+            String k = (String) entry.getKey();
+            String v = (String) entry.getValue();
+            if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k)) {
+                sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
+            } else {
+                sb.append("<" + k + ">" + v + "</" + k + ">");
+            }
+        }
+        sb.append("</xml>");
+        return new String(sb.toString().toString().getBytes(), "utf-8");
+    }
+} 

+ 56 - 0
JsonUtil.java

@@ -0,0 +1,56 @@
+package com.happy.Unitil_elc;
+
+
+import org.apache.commons.text.StringEscapeUtils;
+
+public class JsonUtil {
+
+    private static String getLevelStr(int level) {
+        StringBuilder levelStr = new StringBuilder();
+        for (int levelI = 0; levelI < level; levelI++) {
+            levelStr.append("\t");
+        }
+        return levelStr.toString();
+    }
+
+    public static String JsonFormart(String s) {
+        int level = 0;
+        //存放格式化的json字符串
+        StringBuilder jsonForMatStr = new StringBuilder();
+        for(int index=0;index<s.length();index++)//将字符串中的字符逐个按行输出
+        {
+            //获取s中的每个字符
+            char c = s.charAt(index);
+//          System.out.println(s.charAt(index));
+
+            //level大于0并且jsonForMatStr中的最后一个字符为\n,jsonForMatStr加入\t
+            if (level > 0 && '\n' == jsonForMatStr.charAt(jsonForMatStr.length() - 1)) {
+                jsonForMatStr.append(getLevelStr(level));
+//                System.out.println("123"+jsonForMatStr);
+            }
+            //遇到"{"和"["要增加空格和换行,遇到"}"和"]"要减少空格,以对应,遇到","要换行
+            switch (c) {
+                case '{':
+                case '[':
+                    jsonForMatStr.append(c).append("\n");
+                    level++;
+                    break;
+                case ',':
+                    jsonForMatStr.append(c).append("\n");
+                    break;
+                case '}':
+                case ']':
+                    jsonForMatStr.append("\n");
+                    level--;
+                    jsonForMatStr.append(getLevelStr(level));
+                    jsonForMatStr.append(c);
+                    break;
+                default:
+                    jsonForMatStr.append(c);
+                    break;
+            }
+        }
+        return StringEscapeUtils.unescapeJava(jsonForMatStr.toString());
+    }
+}
+

+ 26 - 0
LeyouCorsConfig.java

@@ -0,0 +1,26 @@
+package com.happy.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.cors.CorsConfiguration;
+import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
+import org.springframework.web.filter.CorsFilter;
+
+@Configuration
+public class LeyouCorsConfig {
+    @Bean
+    public CorsFilter corsFilter() {
+        //1.添加CORS配置信息
+        CorsConfiguration config = new CorsConfiguration();
+        //1) 允许的域(填前台域),不要写*,否则cookie就无法使用了
+        config.addAllowedOrigin("*");
+        config.setAllowCredentials(true);  //2) 是否发送Cookie信息
+        config.addAllowedMethod("*");   //3) 允许的请求方式
+        config.addAllowedHeader("*");  // 4)允许的头信息
+        //2.添加映射路径,我们拦截一切请求
+        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
+        configSource.registerCorsConfiguration("/**", config);
+        //3.返回新的CorsFilter.
+        return new CorsFilter(configSource);
+    }
+}

+ 95 - 0
Login.java

@@ -0,0 +1,95 @@
+package com.happy.Model;
+
+public class Login {
+
+    public Integer id;
+    public String card_number;
+    public String user_name;
+    public String password;
+    public String login_time;
+    public String expire_time;
+    public String access_token;
+    public String open_id;
+    public String code;
+    public String message;
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public String getCard_number() {
+        return card_number;
+    }
+
+    public void setCard_number(String card_number) {
+        this.card_number = card_number;
+    }
+
+    public String getUser_name() {
+        return user_name;
+    }
+
+    public void setUser_name(String user_name) {
+        this.user_name = user_name;
+    }
+
+    public String getPassword() {
+        return password;
+    }
+
+    public void setPassword(String password) {
+        this.password = password;
+    }
+
+    public String getLogin_time() {
+        return login_time;
+    }
+
+    public void setLogin_time(String login_time) {
+        this.login_time = login_time;
+    }
+
+    public String getExpire_time() {
+        return expire_time;
+    }
+
+    public void setExpire_time(String expire_time) {
+        this.expire_time = expire_time;
+    }
+
+    public String getAccess_token() {
+        return access_token;
+    }
+
+    public void setAccess_token(String access_token) {
+        this.access_token = access_token;
+    }
+
+    public String getOpen_id() {
+        return open_id;
+    }
+
+    public void setOpen_id(String open_id) {
+        this.open_id = open_id;
+    }
+
+    public String getCode() {
+        return code;
+    }
+
+    public void setCode(String code) {
+        this.code = code;
+    }
+
+    public String getMessage() {
+        return message;
+    }
+
+    public void setMessage(String message) {
+        this.message = message;
+    }
+}

+ 52 - 0
LoginFilter.java

@@ -0,0 +1,52 @@
+////
+//// Source code recreated from a .class file by IntelliJ IDEA
+//// (powered by Fernflower decompiler)
+////
+//
+//package com.happy.filter;
+//
+//import javax.servlet.*;
+//import javax.servlet.http.HttpServletRequest;
+//import javax.servlet.http.HttpServletResponse;
+//import javax.servlet.http.HttpSession;
+//import java.io.IOException;
+//import java.util.Enumeration;
+//
+//public class LoginFilter implements Filter {
+//	Enumeration param;
+//
+//	public LoginFilter() {
+//	}
+//
+//	public void init(FilterConfig filterConfig) throws ServletException {
+//		this.param = filterConfig.getInitParameterNames();
+//	}
+//
+//	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+//		HttpServletRequest servletRequest = (HttpServletRequest)request;
+//		HttpServletResponse servletResponse = (HttpServletResponse)response;
+//		HttpSession session = servletRequest.getSession();
+//		String path = servletRequest.getRequestURI();
+//		String isLogin = (String)session.getAttribute("isLogin");
+//		if (path.indexOf("login.jsp") <= -1 && path.indexOf("branduserbrandlist.action") <= -1 && path.indexOf("/weixin/") <= -1 && path.indexOf("/loginlogin.action") <= -1 && path.indexOf("/WxPaylog.action") <= -1 && path.indexOf("register2.jsp") <= -1 && path.indexOf("/WxPayregister2.action") <= -1) {
+//			if (isLogin != null && !"".equals(isLogin)) {
+//				chain.doFilter(request, response);
+//			} else {
+//				StringBuffer fileURL = servletRequest.getRequestURL();
+//				if (fileURL.indexOf(".css") > 0 || fileURL.indexOf(".png") > 0 || fileURL.indexOf(".jpg") > 0 || fileURL.indexOf(".bmp") > 0 || fileURL.indexOf(".gif") > 0 || fileURL.indexOf(".apk") > 0 || fileURL.indexOf(".ipa") > 0 || fileURL.indexOf(".woff") > 0 || fileURL.indexOf(".ttf") > 0 || fileURL.indexOf("image.jsp") > 0) {
+//					chain.doFilter(servletRequest, servletResponse);
+//					return;
+//				}
+//
+//				String contextPath = servletRequest.getContextPath();
+//				servletResponse.sendRedirect(contextPath + "/jsp/login.jsp");
+//			}
+//
+//		} else {
+//			chain.doFilter(servletRequest, servletResponse);
+//		}
+//	}
+//
+//	public void destroy() {
+//	}
+//}

+ 2 - 0
MANIFEST.MF

@@ -0,0 +1,2 @@
+Manifest-Version: 1.0
+

+ 49 - 0
MD5Utils.java

@@ -0,0 +1,49 @@
+package com.happy.Until;
+
+import java.security.MessageDigest;
+
+public class MD5Utils {
+
+    /***
+     * MD5加码 生成32位md5码
+     */
+    public static String toMD5(String inStr){
+        MessageDigest md5 = null;
+        try{
+            md5 = MessageDigest.getInstance("MD5");
+        }catch (Exception e){
+            System.out.println(e.toString());
+            e.printStackTrace();
+            return "";
+        }
+        char[] charArray = inStr.toCharArray();
+        byte[] byteArray = new byte[charArray.length];
+
+        for (int i = 0; i < charArray.length; i++)
+            byteArray[i] = (byte) charArray[i];
+        byte[] md5Bytes = md5.digest(byteArray);
+        StringBuffer hexValue = new StringBuffer();
+        for (int i = 0; i < md5Bytes.length; i++){
+            int val = ((int) md5Bytes[i]) & 0xff;
+            if (val < 16)
+                hexValue.append("0");
+            hexValue.append(Integer.toHexString(val));
+        }
+        return hexValue.toString();
+
+    }
+
+    /**
+     * 加密解密算法 执行一次加密,两次解密
+     */
+    public static String unlock(String inStr){
+
+        char[] a = inStr.toCharArray();
+        for (int i = 0; i < a.length; i++){
+            a[i] = (char) (a[i] ^ 't');
+        }
+        String s = new String(a);
+        return s;
+
+    }
+}

+ 34 - 0
MyDate.java

@@ -0,0 +1,34 @@
+package testExport;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Locale;
+
+public class MyDate {
+
+    private static Date getWebsiteDatetime(){
+        String webUrl = "http://www.ntsc.ac.cn"; //中国科学院国家授时中心
+        try {
+            URL url = new URL(webUrl);// 取得资源对象
+            URLConnection uc = url.openConnection();// 生成连接对象
+            uc.connect();// 发出连接
+            long ld = uc.getDate();// 读取网站日期时间
+            Date date = new Date(ld);// 转换为标准时间对象
+            return date;
+        } catch (MalformedURLException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    public static void main(String[] args) {
+        Date da = getWebsiteDatetime();
+        System.out.println(da);
+    }
+}

+ 23 - 0
MyX509TrustManager.java

@@ -0,0 +1,23 @@
+package com.happy.common.http;
+
+import javax.net.ssl.X509TrustManager;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+
+/**
+ * X509TrustManager用于实现SSL证书的安全校验
+ * @author lujunjie
+ * @date   2018/03/01
+ */
+public class MyX509TrustManager implements X509TrustManager {
+    @Override
+    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
+
+    @Override
+    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
+
+    @Override
+    public X509Certificate[] getAcceptedIssuers() {
+        return null;
+    }
+}

+ 63 - 0
OnlineTime.java

@@ -0,0 +1,63 @@
+package com.happy.Until.Time;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Locale;
+
+public class OnlineTime {
+
+    public static String webUrl4 = "http://www.ntsc.ac.cn";//中国科学院国家授时中心
+
+    public static String getWebsiteDatetime(String webUrl){
+        try {
+            URL url = new URL(webUrl);// 取得资源对象
+            URLConnection uc = url.openConnection();// 生成连接对象
+            uc.connect();// 发出连接
+            long ld = uc.getDate();// 读取网站日期时间
+            Date date = new Date(ld);// 转换为标准时间对象
+            System.out.println(date);
+            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 输出北京时间
+            return sdf.format(date);
+        } catch (MalformedURLException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    public static String getWebsiteDateday(String webUrl){
+        try {
+            URL url = new URL(webUrl);// 取得资源对象
+            URLConnection uc = url.openConnection();// 生成连接对象
+            uc.connect();// 发出连接
+            long ld = uc.getDate();// 读取网站日期时间
+            Date date = new Date(ld);// 转换为标准时间对象
+            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");// 输出北京时间
+            return sdf.format(date);
+        } catch (MalformedURLException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    public static String time(){
+        return getWebsiteDatetime(webUrl4);
+    }
+
+    public static  String day(){
+        return getWebsiteDateday(webUrl4);
+    }
+
+    public static void main(String[] args) {
+        System.out.println(day());
+        System.out.println(time());
+    }
+}

+ 12 - 0
PassToken.java

@@ -0,0 +1,12 @@
+package com.happy.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target({ElementType.METHOD, ElementType.TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+public @interface PassToken {
+    boolean required() default true;
+}

+ 76 - 0
Pay.java

@@ -0,0 +1,76 @@
+package com.happy.Model.weixin;
+/**
+ * 充值记录实体来
+ * @author QT-666
+ *
+ */
+public class Pay {
+    private int pay_id;//
+    private int user_id;//用户id
+    private String open_id;//用户相对于公众号的唯一id
+    private String user_name;//用户名称
+    private double pay_money;//支付金额
+    private String pay_time;//支付时间
+    private int pay_type;//支付方式(1微信2支付宝
+    private String pay_no;//订单号
+    //private String pay_state;//F:未支付;T:已支付
+
+    private String user_account;//页面显示作用,表里无此字段
+    
+	public String getUser_account() {
+		return user_account;
+	}
+	public void setUser_account(String user_account) {
+		this.user_account = user_account;
+	}
+	public int getPay_id() {
+		return pay_id;
+	}
+	public void setPay_id(int pay_id) {
+		this.pay_id = pay_id;
+	}
+	public int getUser_id() {
+		return user_id;
+	}
+	public void setUser_id(int user_id) {
+		this.user_id = user_id;
+	}
+	public String getOpen_id() {
+		return open_id;
+	}
+	public void setOpen_id(String open_id) {
+		this.open_id = open_id;
+	}
+	public String getUser_name() {
+		return user_name;
+	}
+	public void setUser_name(String user_name) {
+		this.user_name = user_name;
+	}
+	public double getPay_money() {
+		return pay_money;
+	}
+	public void setPay_money(double pay_money) {
+		this.pay_money = pay_money;
+	}
+	public String getPay_time() {
+		return pay_time;
+	}
+	public void setPay_time(String pay_time) {
+		this.pay_time = pay_time;
+	}
+	public int getPay_type() {
+		return pay_type;
+	}
+	public void setPay_type(int pay_type) {
+		this.pay_type = pay_type;
+	}
+	public String getPay_no() {
+		return pay_no;
+	}
+	public void setPay_no(String pay_no) {
+		this.pay_no = pay_no;
+	}
+    
+    
+}

+ 275 - 0
PayResult.java

@@ -0,0 +1,275 @@
+package com.happy.Model.weixin;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+/**
+ * 微信支付结果返回
+ * 
+ * @author QT-666
+ * 
+ */
+@XmlRootElement(name="xml")
+public class PayResult {
+	private String appid;// 微信分配的公众账号ID(企业号corpid即为此appId)
+	private String attach;//附加数据,在查询API和支付通知中原样返回,可作为自定义参数使用。
+	private String bank_type;// 银行类型,采用字符串类型的银行标识,银行类型见银行列表
+	private String fee_type;// 货币类型,符合ISO4217标准的三位字母代码,默认人民币:CNY,其他值列表详见货币类型
+	private String is_subscribe;// 用户是否关注公众账号,Y-关注,N-未关注,仅在公众账号类型支付有效
+	private String mch_id;// 微信支付分配的商户号
+	private String nonce_str;// 随机字符串,不长于32位
+	private String openid;// 用户在商户appid下的唯一标识
+	private String out_trade_no;// 商户系统内部订单号,要求32个字符内,只能是数字、大小写字母_-|*@
+								// ,且在同一个商户号下唯一。
+	private String result_code;// SUCCESS/FAIL
+	private String return_code;// 此字段是通信标识,非交易标识,交易是否成功需要查看result_code来判断
+	private String sign;// 签名,详见签名算法
+	private String sub_mch_id;//
+	private String time_end;// 支付完成时间,格式为yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010。其他详见时间规则
+	private int total_fee;// 订单总金额,单位为分
+	private String trade_type;// JSAPI、NATIVE、APP
+	private String transaction_id;// 微信支付订单号
+	private int cash_fee;// 现金金额
+	
+	private String device_info; //微信支付分配的终端设备号,
+    private String sign_type;//签名类型,目前支持HMAC-SHA256和MD5,默认为MD5
+    private String settlement_total_fee ;//应结订单金额=订单金额-非充值代金券金额,应结订单金额<=订单金额。 
+    private String cash_fee_type;//货币类型,符合ISO4217标准的三位字母代码,默认人民币:CNY,其他值列表详见货币类型
+    private String  coupon_fee;//代金券金额<=订单金额,订单金额-代金券金额=现金支付金额,详见支付金额
+    private String coupon_count;//代金券使用数量
+    private String coupon_type_$n;// CASH--充值代金券 NO_CASH---非充值代金券 仅在使用了免充值代金券时有返回(取值:CASH、NO_CASH)。$n为下标,从0开始编号,举例:coupon_type_0
+    private String coupon_id_$n;//代金券ID,$n为下标,从0开始编号
+    private String coupon_fee_$n;//单个代金券支付金额,$n为下标,从0开始编号
+    
+    
+
+	public String getDevice_info() {
+		return device_info;
+	}
+
+	public void setDevice_info(String device_info) {
+		this.device_info = device_info;
+	}
+
+	public String getSign_type() {
+		return sign_type;
+	}
+
+	public void setSign_type(String sign_type) {
+		this.sign_type = sign_type;
+	}
+
+	public String getSettlement_total_fee() {
+		return settlement_total_fee;
+	}
+
+	public void setSettlement_total_fee(String settlement_total_fee) {
+		this.settlement_total_fee = settlement_total_fee;
+	}
+
+	public String getCash_fee_type() {
+		return cash_fee_type;
+	}
+
+	public void setCash_fee_type(String cash_fee_type) {
+		this.cash_fee_type = cash_fee_type;
+	}
+
+	public String getCoupon_fee() {
+		return coupon_fee;
+	}
+
+	public void setCoupon_fee(String coupon_fee) {
+		this.coupon_fee = coupon_fee;
+	}
+
+	public String getCoupon_count() {
+		return coupon_count;
+	}
+
+	public void setCoupon_count(String coupon_count) {
+		this.coupon_count = coupon_count;
+	}
+
+	public String getCoupon_type_$n() {
+		return coupon_type_$n;
+	}
+
+	public void setCoupon_type_$n(String coupon_type_$n) {
+		this.coupon_type_$n = coupon_type_$n;
+	}
+
+	public String getCoupon_id_$n() {
+		return coupon_id_$n;
+	}
+
+	public void setCoupon_id_$n(String coupon_id_$n) {
+		this.coupon_id_$n = coupon_id_$n;
+	}
+
+	public String getCoupon_fee_$n() {
+		return coupon_fee_$n;
+	}
+
+	public void setCoupon_fee_$n(String coupon_fee_$n) {
+		this.coupon_fee_$n = coupon_fee_$n;
+	}
+
+	public String getAppid() {
+		return appid;
+	}
+
+	public void setAppid(String appid) {
+		this.appid = appid;
+	}
+
+	public String getAttach() {
+		return attach;
+	}
+
+	public void setAttach(String attach) {
+		this.attach = attach;
+	}
+
+	public String getBank_type() {
+		return bank_type;
+	}
+
+	public void setBank_type(String bank_type) {
+		this.bank_type = bank_type;
+	}
+
+	public String getFee_type() {
+		return fee_type;
+	}
+
+	public void setFee_type(String fee_type) {
+		this.fee_type = fee_type;
+	}
+
+	public String getIs_subscribe() {
+		return is_subscribe;
+	}
+
+	public void setIs_subscribe(String is_subscribe) {
+		this.is_subscribe = is_subscribe;
+	}
+
+	public String getMch_id() {
+		return mch_id;
+	}
+
+	public void setMch_id(String mch_id) {
+		this.mch_id = mch_id;
+	}
+
+	public String getNonce_str() {
+		return nonce_str;
+	}
+
+	public void setNonce_str(String nonce_str) {
+		this.nonce_str = nonce_str;
+	}
+
+	public String getOpenid() {
+		return openid;
+	}
+
+	public void setOpenid(String openid) {
+		this.openid = openid;
+	}
+
+	public String getOut_trade_no() {
+		return out_trade_no;
+	}
+
+	public void setOut_trade_no(String out_trade_no) {
+		this.out_trade_no = out_trade_no;
+	}
+
+	public String getResult_code() {
+		return result_code;
+	}
+
+	public void setResult_code(String result_code) {
+		this.result_code = result_code;
+	}
+
+	public String getReturn_code() {
+		return return_code;
+	}
+
+	public void setReturn_code(String return_code) {
+		this.return_code = return_code;
+	}
+
+	public String getSign() {
+		return sign;
+	}
+
+	public void setSign(String sign) {
+		this.sign = sign;
+	}
+
+	public String getSub_mch_id() {
+		return sub_mch_id;
+	}
+
+	public void setSub_mch_id(String sub_mch_id) {
+		this.sub_mch_id = sub_mch_id;
+	}
+
+	public String getTime_end() {
+		return time_end;
+	}
+
+	public void setTime_end(String time_end) {
+		this.time_end = time_end;
+	}
+
+	public int getTotal_fee() {
+		return total_fee;
+	}
+
+	public void setTotal_fee(int total_fee) {
+		this.total_fee = total_fee;
+	}
+
+	public String getTrade_type() {
+		return trade_type;
+	}
+
+	public void setTrade_type(String trade_type) {
+		this.trade_type = trade_type;
+	}
+
+	public String getTransaction_id() {
+		return transaction_id;
+	}
+
+	public void setTransaction_id(String transaction_id) {
+		this.transaction_id = transaction_id;
+	}
+
+	public int getCash_fee() {
+		return cash_fee;
+	}
+
+	public void setCash_fee(int cash_fee) {
+		this.cash_fee = cash_fee;
+	}
+
+	@Override
+	public String toString() {
+		return "PayResult [appid=" + appid + ", attach=" + attach
+				+ ", bank_type=" + bank_type + ", fee_type=" + fee_type
+				+ ", is_subscribe=" + is_subscribe + ", mch_id=" + mch_id
+				+ ", nonce_str=" + nonce_str + ", openid=" + openid
+				+ ", out_trade_no=" + out_trade_no + ", result_code="
+				+ result_code + ", return_code=" + return_code + ", sign="
+				+ sign + ", sub_mch_id=" + sub_mch_id + ", time_end="
+				+ time_end + ", total_fee=" + total_fee + ", trade_type="
+				+ trade_type + ", transaction_id=" + transaction_id
+				+ ", cash_fee=" + cash_fee ;
+	}
+   
+}

+ 128 - 0
PayWxUtil.java

@@ -0,0 +1,128 @@
+package com.happy.Until.weixin;
+
+import org.apache.commons.codec.digest.DigestUtils;
+
+import java.security.MessageDigest;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+/**
+ * Created by Song on 2016/11/8. mail: 1147649695@qq.com 微信支付相关工具类
+ */
+public class PayWxUtil {
+	// 上一次订单请求日期
+	private static Date preDay = new Date();
+	// 当前订单日期
+	private static Date curDay = new Date();
+	// 用于记录已产生的订单号
+	private static Set<Long> numPoul = new HashSet<Long>();
+
+	/**
+	 * 获得签名
+	 * 
+	 * @param params
+	 *            待编码参数,参数值为空不传入
+	 * @param key
+	 *            key设置路径:微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置
+	 * @return
+	 */
+	public static String getSign(Map<String, String> params, String key)
+			throws Exception {
+		List<String> list = new ArrayList<String>(params.keySet());
+		Collections.sort(list, new DictionaryCompare());
+		StringBuffer sb = new StringBuffer();
+		for (String keyVal : list) {
+			if (params.get(keyVal) != null) {
+				sb.append(keyVal + "=" + params.get(keyVal) + "&");
+			}
+		}
+		sb.append("key=" + key);
+		return DigestUtils
+				.md5Hex(new String(sb.toString().getBytes(), "utf-8"))
+				.toUpperCase();
+	}
+
+	/**
+	 * 获得随机字符串
+	 * 
+	 * @return
+	 */
+	public static String getNonceStr() {
+		Random random = new Random();
+		long val = random.nextLong();
+		String res = DigestUtils.md5Hex(val + "yzx").toUpperCase();
+		if (32 < res.length())
+			return res.substring(0, 32);
+		else
+			return res;
+	}
+
+	/**
+	 * 获取订单号 商户订单号(每个订单号必须唯一) 组成:mch_id+yyyymmdd+10位一天内不能重复的数字。
+	 * 
+	 * @param mchId
+	 * @return
+	 */
+	public static String getMchBillno(String mchId) {
+		Random random = new Random();
+		long val = random.nextLong() % 10000000000L;// 获得0-9999999999内的数字
+		curDay = new Date();
+		// 隔天清空
+		if (curDay.after(preDay))
+			numPoul.clear();
+		while (numPoul.contains(val)) {
+			val = random.nextLong() % 10000000000L;
+		}
+		numPoul.add(val);
+		preDay = curDay;
+		// 按要求,日期格式化输出
+		DateFormat df = new SimpleDateFormat("yyyymmdd");
+		return mchId + df.format(curDay) + format(val + "", 10);
+	}
+
+	/**
+	 * 将字符串str按长度在前面添0补齐
+	 * 
+	 * @param str
+	 * @param length
+	 * @return
+	 */
+	private static String format(String str, int length) {
+		String pre = "0000000000";
+		int len = str.length();
+		if (10 <= len)
+			return str.substring(0, 10);
+		else
+			return pre.substring(0, 10 - len).concat(str);
+	}
+
+	// SHA1加密方法,jssdk签名算法
+	public static String getSha1(String str) {
+		if (str == null || str.length() == 0) {
+			return null;
+		}
+		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
+				'a', 'b', 'c', 'd', 'e', 'f' };
+		try {
+			MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
+			mdTemp.update(str.getBytes("UTF-8"));
+
+			byte[] md = mdTemp.digest();
+			int j = md.length;
+			char buf[] = new char[j * 2];
+			int k = 0;
+			for (int i = 0; i < j; i++) {
+				byte byte0 = md[i];
+				buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
+				buf[k++] = hexDigits[byte0 & 0xf];
+			}
+			return new String(buf);
+		} catch (Exception e) {
+			// TODO: handle exception
+			return null;
+		}
+	}
+
+}
+

+ 61 - 0
Price.java

@@ -0,0 +1,61 @@
+package com.happy.Model;
+
+import java.math.BigDecimal;
+
+public class Price {
+
+    public int id;
+    public String name;
+    public double price;
+    public int state;
+    public String time;
+    public String time2;
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public double getPrice() {
+        return price;
+    }
+
+    public void setPrice(double price) {
+        this.price = price;
+    }
+
+    public int getState() {
+        return state;
+    }
+
+    public void setState(int state) {
+        this.state = state;
+    }
+
+    public String getTime() {
+        return time;
+    }
+
+    public void setTime(String time) {
+        this.time = time;
+    }
+
+    public String getTime2() {
+        return time2;
+    }
+
+    public void setTime2(String time2) {
+        this.time2 = time2;
+    }
+}

+ 23 - 0
Propel.java

@@ -0,0 +1,23 @@
+package com.happy.Model;
+
+public class Propel {
+
+    public String build;
+    public String size;
+
+    public String getBuild() {
+        return build;
+    }
+
+    public void setBuild(String build) {
+        this.build = build;
+    }
+
+    public String getSize() {
+        return size;
+    }
+
+    public void setSize(String size) {
+        this.size = size;
+    }
+}

+ 30 - 0
PropelDao.java

@@ -0,0 +1,30 @@
+package com.happy.dao;
+
+import com.alibaba.fastjson.JSONObject;
+import com.happy.Model.Build_elec;
+import com.happy.Model.Detail_elc;
+import com.happy.Model.ElecTotal;
+import com.happy.Model.WaterTj;
+
+import java.util.List;
+
+public interface PropelDao {
+
+    public List<JSONObject> query();
+
+    public List<Build_elec> queryEt();
+
+    public int updateUseSize(String pointid, double use_size);
+
+    public List<JSONObject> queryElecT();
+
+    public List<WaterTj> queryWaterTj();
+
+    public int updateWaterUseSize(String pointid, double use_size);
+
+    public List<JSONObject> queryWaterT();
+
+    public List<Detail_elc> findAll(String sqlx);
+
+    public int total(String sqlx);
+}

+ 186 - 0
PropelDaoImpl.java

@@ -0,0 +1,186 @@
+package com.happy.dao.impl;
+
+import com.alibaba.fastjson.JSONObject;
+import com.happy.Model.*;
+import com.happy.dao.PropelDao;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.jdbc.core.BeanPropertyRowMapper;
+import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
+import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
+import org.springframework.stereotype.Repository;
+
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+@Repository("PropelDao")
+public class PropelDaoImpl implements PropelDao {
+
+    @Autowired
+    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
+
+    public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
+        return namedParameterJdbcTemplate;
+    }
+
+    public void setNamedParameterJdbcTemplate(
+            NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
+        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
+    }
+
+    public List<JSONObject> query(){
+        List<JSONObject> lj = new ArrayList<JSONObject>();
+        String build = "case when build='1栋' then 'qs01' \n" +
+                "when build='2栋' then 'qs02' \n" +
+                "when build='3栋' then 'qs03'\n" +
+                "when build='4栋' then 'qs04'\n" +
+                "when build='5栋' then 'qs05'\n" +
+                "when build='6栋' then 'qs06'\n" +
+                "when build='7栋' then 'qs07'\n" +
+                "when build='8栋' then 'qs08'\n" +
+                "when build='9栋' then 'qs09'\n" +
+                "when build='10栋' then 'qs10'\n" +
+                "when build='11栋' then 'qs11'\n" +
+                "when build='12栋' then 'qs12' end as build";
+        String sql = "select "+build+", CONVERT(SUM(use_size), decimal(10, 2)) as size from (select a.id, a.`begin_time`, a.`device_code`, a.`use_size`, b.`build` from `consume` a  left join `build_water` b on a.`device_code`=b.`user_id` where b.build is not null ) a group by build";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        List<Propel> list = namedParameterJdbcTemplate.query(sql, sps,
+                new BeanPropertyRowMapper<Propel>(Propel.class));
+        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        String time = sf.format(new Date());
+        if (list != null && list.size() > 0) {
+            for (int i=0; i<list.size();i++){
+                JSONObject json = new JSONObject();
+                json.put("buildCode", list.get(i).getBuild());
+                json.put("currentAggr", list.get(i).getSize());
+                json.put("energyType", "3");
+                json.put("updateTime", time);
+                lj.add(json);
+            }
+            return lj;
+        }
+        return null;
+    }
+
+    public List<Build_elec> queryEt(){
+        String sql="select * from build_elec where pointid!='0'";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        List<Build_elec> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Build_elec>(Build_elec.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public int updateUseSize(String pointid, double use_size){
+        String sql = "update build_elec set use_size=:use_size where pointid=:pointid";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("pointid", pointid);
+        sps.addValue("use_size", use_size);
+        return namedParameterJdbcTemplate.update(sql, sps);
+    }
+
+    public List<JSONObject> queryElecT(){
+        List<JSONObject> lj = new ArrayList<JSONObject>();
+        String build = "case when build='1栋' then 'qs01' \n" +
+                "when build='2栋' then 'qs02' \n" +
+                "when build='3栋' then 'qs03'\n" +
+                "when build='4栋' then 'qs04'\n" +
+                "when build='5栋' then 'qs05'\n" +
+                "when build='6栋' then 'qs06'\n" +
+                "when build='7栋' then 'qs07'\n" +
+                "when build='8栋' then 'qs08'\n" +
+                "when build='9栋' then 'qs09'\n" +
+                "when build='10栋' then 'qs10'\n" +
+                "when build='11栋' then 'qs11'\n" +
+                "when build='12栋' then 'qs12' end as build";
+        String sql = "select "+build+", CONVERT(SUM(use_size), decimal(10, 2)) as use_size from `build_elec` group by build";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        List<ElecTotal> list = namedParameterJdbcTemplate.query(sql, sps,
+                new BeanPropertyRowMapper<ElecTotal>(ElecTotal.class));
+        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        String time = sf.format(new Date());
+        if (list != null && list.size() > 0) {
+            for (int i=0; i<list.size();i++){
+                JSONObject json = new JSONObject();
+                json.put("buildCode", list.get(i).getBuild());
+                json.put("currentAggr", list.get(i).getUse_size());
+                json.put("energyType", "1");
+                json.put("updateTime", time);
+                lj.add(json);
+            }
+            return lj;
+        }
+        return null;
+    }
+
+    // 查询水表信息
+    public List<WaterTj> queryWaterTj(){
+        String sql="select * from waterTongji where `state`=1";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        List<WaterTj> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<WaterTj>(WaterTj.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    // 更新冷水使用
+    public int updateWaterUseSize(String pointid, double use_size){
+        String sql = "update waterTongji set use_size=:use_size where pointid=:pointid";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("pointid", pointid);
+        sps.addValue("use_size", use_size);
+        return namedParameterJdbcTemplate.update(sql, sps);
+    }
+
+    // 按楼栋查水
+    public List<JSONObject> queryWaterT(){
+        List<JSONObject> lj = new ArrayList<JSONObject>();
+        String build = "case when build='1栋' then 'qs01' \n" +
+                "when build='2栋' then 'qs02' \n" +
+                "when build='3栋' then 'qs03'\n" +
+                "when build='4栋' then 'qs04'\n" +
+                "when build='5栋' then 'qs05'\n" +
+                "when build='6栋' then 'qs06'\n" +
+                "when build='7栋' then 'qs07'\n" +
+                "when build='8栋' then 'qs08'\n" +
+                "when build='9栋' then 'qs09'\n" +
+                "when build='10栋' then 'qs10'\n" +
+                "when build='11栋' then 'qs11'\n" +
+                "when build='12栋' then 'qs12' end as build";
+        String sql = "select "+build+", CONVERT(SUM(use_size), decimal(10, 2)) as use_size from `waterTongji` group by build";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        List<ElecTotal> list = namedParameterJdbcTemplate.query(sql, sps,
+                new BeanPropertyRowMapper<ElecTotal>(ElecTotal.class));
+        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        String time = sf.format(new Date());
+        if (list != null && list.size() > 0) {
+            for (int i=0; i<list.size();i++){
+                JSONObject json = new JSONObject();
+                json.put("buildCode", list.get(i).getBuild());
+                json.put("currentAggr", list.get(i).getUse_size());
+                json.put("energyType", "2");
+                json.put("updateTime", time);
+                lj.add(json);
+            }
+            return lj;
+        }
+        return null;
+    }
+
+    // 有条件的查询
+    public List<Detail_elc> findAll(String sqlx) {
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        List<Detail_elc> list=namedParameterJdbcTemplate.query(sqlx, sps,new BeanPropertyRowMapper<Detail_elc>(Detail_elc.class));
+        return list != null && list.size() > 0 ? list : null;
+    }
+
+    // 查询总记录数
+    public int total(String sqlx) {
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        return namedParameterJdbcTemplate.queryForInt(sqlx, sps);
+    }
+
+}

+ 30 - 0
PropelService.java

@@ -0,0 +1,30 @@
+package com.happy.service;
+
+import com.alibaba.fastjson.JSONObject;
+import com.happy.Model.Build_elec;
+import com.happy.Model.Detail_elc;
+import com.happy.Model.ElecTotal;
+import com.happy.Model.WaterTj;
+
+import java.util.List;
+
+public interface PropelService {
+
+    public List<JSONObject> query();
+
+    public List<Build_elec> queryEt();
+
+    public int updateUseSize(String pointid, double use_size);
+
+    public List<JSONObject> queryElecT();
+
+    public List<WaterTj> queryWaterTj();
+
+    public int updateWaterUseSize(String pointid, double use_size);
+
+    public List<JSONObject> queryWaterT();
+
+    public List<Detail_elc> findAll(String sqlx);
+
+    public int total(String sqlx);
+}

+ 57 - 0
PropelServiceImpl.java

@@ -0,0 +1,57 @@
+package com.happy.service.impl;
+
+import com.alibaba.fastjson.JSONObject;
+import com.happy.Model.Build_elec;
+import com.happy.Model.Detail_elc;
+import com.happy.Model.ElecTotal;
+import com.happy.Model.WaterTj;
+import com.happy.dao.PropelDao;
+import com.happy.service.PropelService;
+import flexjson.JSON;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.util.List;
+
+@Service("PropelService")
+public class PropelServiceImpl implements PropelService {
+
+    @Autowired
+    public PropelDao propelDao;
+
+    public List<JSONObject> query(){
+        return propelDao.query();
+    }
+
+    public List<Build_elec> queryEt(){
+        return propelDao.queryEt();
+    }
+
+    public int updateUseSize(String pointid, double use_size){
+        return propelDao.updateUseSize(pointid, use_size);
+    }
+
+    public List<JSONObject> queryElecT(){
+        return propelDao.queryElecT();
+    }
+
+    public List<WaterTj> queryWaterTj(){
+        return propelDao.queryWaterTj();
+    }
+
+    public int updateWaterUseSize(String pointid, double use_size){
+        return propelDao.updateWaterUseSize(pointid, use_size);
+    }
+
+    public List<JSONObject> queryWaterT(){
+        return propelDao.queryWaterT();
+    }
+
+    public List<Detail_elc> findAll(String sqlx){
+        return propelDao.findAll(sqlx);
+    };
+
+    public int total(String sqlx){
+        return propelDao.total(sqlx);
+    };
+}

+ 408 - 0
Propelling.java

@@ -0,0 +1,408 @@
+package com.happy.action;
+
+import com.alibaba.fastjson.JSONObject;
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+import com.happy.Model.*;
+import com.happy.Until.ResUtil;
+import com.happy.Until.ResponseUtil;
+import com.happy.common.http.HttpsClient;
+import com.happy.service.ConsumeService;
+import com.happy.service.ElecService;
+import com.happy.service.PropelService;
+import com.opensymphony.xwork2.ActionSupport;
+import org.apache.struts2.ServletActionContext;
+import org.apache.struts2.interceptor.ServletRequestAware;
+import testExport.DataClient;
+import testExport.Test;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+
+public class Propelling  extends ActionSupport implements ServletRequestAware {
+
+    private HttpServletRequest request;
+    public HttpServletResponse response;
+
+    @Resource
+    public PropelService propelService;
+    @Resource
+    public ConsumeService consumeService;
+    @Resource
+    public ElecService elecService;
+
+    public int page; // 当前页
+    public int rows;// 每页显示的行数rows
+    public String dom;
+    public String dataTime;
+    public String build;
+
+    public HttpServletRequest getRequest() {
+        return request;
+    }
+
+    public void setRequest(HttpServletRequest request) {
+        this.request = request;
+    }
+
+    public void setServletRequest(HttpServletRequest request) {
+        this.request = request;
+    }
+
+    public HttpServletResponse getResponse() {
+        return response;
+    }
+
+    public void setResponse(HttpServletResponse response) {
+        this.response = response;
+    }
+
+    public String getDom() {
+        return dom;
+    }
+
+    public void setDom(String dom) {
+        this.dom = dom;
+    }
+
+    public String getDataTime() {
+        return dataTime;
+    }
+
+    public void setDataTime(String dataTime) {
+        this.dataTime = dataTime;
+    }
+
+    public int getPage() {
+        return page;
+    }
+
+    public void setPage(int page) {
+        this.page = page;
+    }
+
+    public int getRows() {
+        return rows;
+    }
+
+    public void setRows(int rows) {
+        this.rows = rows;
+    }
+
+    public String getBuild() {
+        return build;
+    }
+
+    public void setBuild(String build) {
+        this.build = build;
+    }
+
+    // 热水推送
+    public String load(){
+        List<JSONObject> json = propelService.query();
+        String result = "";
+        for (int i=0; i<json.size(); i++) {
+            result = HttpsClient.sendJson2("https://chtech.ncjti.edu.cn/bigdata-api/api/energy/energyDataUpload", json.get(i));
+        }
+        JSONObject resultJson = new JSONObject();
+        resultJson.put("msg", result);
+        ResponseUtil.writeJson(ServletActionContext.getResponse(),
+                resultJson.toString());
+        return null;
+    }
+
+    // 电费更新
+    public String getElecT() throws Exception {
+        Gson gson=new Gson();
+        JSONObject resultJson = new JSONObject();
+        List<Build_elec> ta = propelService.queryEt();
+        for (int i=0; i<ta.size(); i++){
+            System.out.println(ta.get(i).getPointid());
+            DataClient.getToken();
+            JSONObject jb = DataClient.getPowerLastHistoryCumulant(ta.get(i).getPointid());
+            System.out.println(jb);
+            if (jb == null){
+                resultJson.put("mess", "未查询到户号!");
+                ResUtil.write(resultJson, ServletActionContext.getResponse());
+                return null;
+            }
+            try {
+                Object data = jb.get("data");
+                HashMap<String, String> userMoney = gson.fromJson(data.toString(), new TypeToken<HashMap<String, String>>() {}.getType());
+                double elcColumn = Double.parseDouble(userMoney.get("bm"));
+                propelService.updateUseSize(ta.get(i).getPointid(), elcColumn);
+            }catch (Exception e){
+                System.out.println("更新失败");
+            }
+        }
+        resultJson.put("msg", "更新完毕");
+        ResponseUtil.writeJson(ServletActionContext.getResponse(),
+                resultJson.toString());
+        return null;
+    }
+
+    // 电费推送
+    public String ElecByBuild(){
+        List<JSONObject> et = propelService.queryElecT();
+        String result = "";
+        if (et!=null){
+            for (int i=0; i<et.size(); i++){
+                System.out.println(et.get(i));
+                result = HttpsClient.sendJson2("https://chtech.ncjti.edu.cn/bigdata-api/api/energy/energyDataUpload", et.get(i));
+            }
+        }
+        JSONObject resultJson = new JSONObject();
+        resultJson.put("msg", result);
+        ResponseUtil.writeJson(ServletActionContext.getResponse(),
+                resultJson.toString());
+        return null;
+    }
+
+    // 水费更新
+    public String getWaterT() throws Exception {
+        Gson gson=new Gson();
+        JSONObject resultJson = new JSONObject();
+        List<WaterTj> ta = propelService.queryWaterTj();
+        for (int i=0; i<ta.size(); i++){
+            System.out.println(ta.get(i).getPointid());
+            DataClient.getToken();
+            JSONObject jb = DataClient.getPowerLastHistoryCumulantw(ta.get(i).getPointid());
+            //System.out.println(jb);
+            if (jb == null){
+                System.out.println("未查到:"+ta.get(i).getPointid());
+            }else {
+                try {
+                    Object data = jb.get("data");
+                    HashMap<String, String> userMoney = gson.fromJson(data.toString(), new TypeToken<HashMap<String, String>>() {
+                    }.getType());
+                    double elcColumn = Double.parseDouble(userMoney.get("bm"));
+                    propelService.updateWaterUseSize(ta.get(i).getPointid(), elcColumn);
+                } catch (Exception e) {
+                    System.out.println("更新失败");
+                }
+            }
+        }
+        resultJson.put("msg", "更新完毕");
+        ResponseUtil.writeJson(ServletActionContext.getResponse(),
+                resultJson.toString());
+        return null;
+    }
+
+    // 水费推送
+    public String waterByBuild(){
+        List<JSONObject> et = propelService.queryWaterT();
+        String result = "";
+        if (et!=null){
+            for (int i=0; i<et.size(); i++){
+                System.out.println(et.get(i));
+                result = HttpsClient.sendJson2("https://chtech.ncjti.edu.cn/bigdata-api/api/energy/energyDataUpload", et.get(i));
+            }
+        }
+        JSONObject resultJson = new JSONObject();
+        resultJson.put("msg", result);
+        ResponseUtil.writeJson(ServletActionContext.getResponse(),
+                resultJson.toString());
+        return null;
+    }
+
+    // 下载电费使用详情
+    public String bm(){
+        JSONObject resultJson = new JSONObject();
+        Gson gson = new Gson();
+        Calendar cal = Calendar.getInstance();
+        // 往前多少天的访客
+        cal.add(Calendar.DATE,   -1);
+        Calendar cal2 = Calendar.getInstance();
+        // 往前多少天的访客
+        cal2.add(Calendar.DATE,   -0);
+        String startTime = new SimpleDateFormat( "yyyyMMdd").format(cal.getTime());
+        String endTime = new SimpleDateFormat( "yyyyMMdd").format(cal2.getTime());
+        System.out.println("开始时间:"+startTime);
+        System.out.println("结束时间:"+endTime);
+        List<Build_elec> lists = elecService.queryAll();
+        for (int i=0; i<lists.size(); i++){
+            try {
+                DataClient.getToken();
+                JSONObject json = DataClient.getHistoryCumulant(lists.get(i).getPointid(), startTime, endTime);
+                Object obj = json.get("data");
+                List<HistoryBm> lh = gson.fromJson(obj.toString(), new TypeToken<List<HistoryBm>>() {}.getType());
+                for (int j = 0; j < lh.size(); j++) {
+                    Detail_elc detail_elc = new Detail_elc();
+                    detail_elc.setBuild(lists.get(i).getBuild());
+                    detail_elc.setDom(lists.get(i).getDom());
+                    detail_elc.setPointid(lists.get(i).getPointid());
+                    detail_elc.setDataTime(lh.get(j).getDataTime().substring(0, 10));
+                    detail_elc.setBm(lh.get(j).getBm());
+                    List<Detail_elc> ld = elecService.queryByTimeAndPoint(lists.get(i).getPointid(), lh.get(j).getDataTime().substring(0, 10));
+                    if (ld == null ) {
+                        elecService.insertDetail(detail_elc);
+                        System.out.println(lists.get(i).getPointid() + "==" + lh.get(j).getDataTime().substring(0, 10));
+                    }
+                }
+            }catch (Exception e){
+                System.out.println(lists.get(i).getPointid()+"未查到");
+            }
+        }
+        resultJson.put("msg", "插入完成");
+        System.out.println("表码下载完成");
+        ResponseUtil.writeJson(ServletActionContext.getResponse(),
+                resultJson.toString());
+        return null;
+    }
+
+    // 更新每日使用电量
+    public String updateUse() throws ParseException {
+        JSONObject resultJson = new JSONObject();
+        List<Detail_elc> ld = elecService.queryUse();
+        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
+        Calendar c = Calendar.getInstance();
+        if (ld!=null) {
+            for (int i = 0; i < ld.size(); i++) {
+                // 获取某个日期前一天
+                String day_time = ld.get(i).getDataTime();
+                Date date = dateFormat.parse(day_time);
+                c.setTime(date);
+                int day = c.get(Calendar.DATE);
+                c.set(Calendar.DATE, day - 1);
+                String dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
+                List<Detail_elc> use_day = elecService.queryByTimeAndPoint(ld.get(i).getPointid(), ld.get(i).getDataTime());
+                List<Detail_elc> use_before = elecService.queryByTimeAndPoint(ld.get(i).getPointid(), dayBefore);
+                if (use_before != null) {
+                    double use_size = use_day.get(0).getBm() - use_before.get(0).getBm();
+                    elecService.updateUse(ld.get(i).getPointid(), ld.get(i).getDataTime(), use_size);
+                    System.out.println(ld.get(i).getPointid() + "====" + ld.get(i).getDataTime());
+                } else {
+                    elecService.updateUseState(ld.get(i).getPointid(), ld.get(i).getDataTime());
+                }
+            }
+        }
+        resultJson.put("msg", "更新成功!");
+        System.out.println("用电量更新完");
+        ResponseUtil.writeJson(ServletActionContext.getResponse(),
+                resultJson.toString());
+        return null;
+    }
+
+    // 更新每日充值
+    public String updateRe(){
+        JSONObject resultJson = new JSONObject();
+        List<Detail_elc> de = elecService.queryRe();
+        if (de!=null) {
+            for (int i = 0; i < de.size(); i++) {
+                List<Recharge_elc> re = elecService.queryByPointAndDay(de.get(i).getPointid(), de.get(i).getDataTime());
+                if (re != null) {
+                    double b = 0;
+                    for (int j = 0; j < re.size(); j++) {
+                        b = b + re.get(j).getAccount();
+                    }
+                    elecService.updateRe(de.get(i).getPointid(), de.get(i).getDataTime(), b);
+                } else {
+                    elecService.updateReState(de.get(i).getPointid(), de.get(i).getDataTime());
+                }
+
+            }
+        }
+        resultJson.put("msg", "更新成功!");
+        System.out.println("充值更新完");
+        ResponseUtil.writeJson(ServletActionContext.getResponse(),
+                resultJson.toString());
+        return null;
+    }
+
+    // 更新每日剩余可用电量
+    public String updateUsable() throws Exception {
+        JSONObject resultJson = new JSONObject();
+        Calendar cal = Calendar.getInstance();
+        // 往前多少天的访客
+        cal.add(Calendar.DATE,   -1);
+        String day = new SimpleDateFormat( "yyyy-MM-dd").format(cal.getTime());
+        List<Detail_elc> de = elecService.queryUsable();
+        if (de!=null) {
+            for (int i = 0; i < de.size(); i++) {
+                List<Build_elec> re = elecService.queryBuildByPoint(de.get(i).getPointid());
+                if (re != null) {
+                    String user_id = re.get(0).getUser_id();
+                    DataClient.getToken();
+                    JSONObject jb = DataClient.getAccountInfo(user_id);
+                    if (jb != null) {
+                        try {
+                            Object data = jb.get("data");
+                            Gson gson = new Gson();
+                            HashMap<String, String> userMoney = gson.fromJson(data.toString(), new TypeToken<HashMap<String, String>>() {
+                            }.getType());
+                            double elcMoney = Double.parseDouble(userMoney.get("usablemoney"));
+                            Double amount = 0.00;
+                            List<Price> elcPrice = consumeService.water_price("电费");
+                            amount = elcMoney / elcPrice.get(0).getPrice();  // 剩余电量
+                            elecService.updateUsable(de.get(i).getPointid(), day, amount);
+                        } catch (Exception e) {
+                            e.printStackTrace();
+                        }
+                    } else {
+                        elecService.updateUsableState(de.get(i).getPointid(), day);
+                    }
+                }
+            }
+        }
+        resultJson.put("msg", "更新成功!");
+        System.out.println("可用余额更新完");
+        ResponseUtil.writeJson(ServletActionContext.getResponse(),
+                resultJson.toString());
+        return null;
+    }
+
+    public String queryDetail() {
+        net.sf.json.JSONObject resultJson = new net.sf.json.JSONObject();
+        StringBuilder sb = new StringBuilder("select * from `detail_elc` where 1=1 ");
+        StringBuilder sb2 = new StringBuilder("select count(*) from `detail_elc` where 1=1 ");
+        if (this.build != null){
+            sb.append(" and build='" + this.build + "'");
+            sb2.append(" and build='" + this.build + "'");
+        }
+        if (this.dom != null) {
+            sb.append(" and dom='" + this.dom + "'");
+            sb2.append(" and dom='" + this.dom + "'");
+        }
+        if (this.dataTime != null) {
+            sb.append(" and dataTime = '" + this.dataTime + "'");
+            sb2.append(" and dataTime = '" + this.dataTime + "'");
+        }
+        int start = (page - 1) * rows;// 每页的起始下标
+        sb.append(" order by dom,dataTime desc limit "+start+", "+rows);
+        System.out.println(sb);
+        int total = this.propelService.total(sb2.toString());
+        System.out.println(total);
+        List<Detail_elc> pp = this.propelService.findAll(sb.toString());
+        System.out.println(pp);
+        if (pp == null) {
+            resultJson.put("rows", "");
+            resultJson.put("total", 0);
+        } else {
+            resultJson.put("rows", pp);
+            // int total = listAll.size();
+            resultJson.put("total", total);// 总记录数
+            int totalPage = total % rows == 0 ? (total / rows)
+                    : (total / rows) + 1;// 总页数
+            resultJson.put("totalPage", totalPage);
+            resultJson.put("currentPage", page);// 当前页
+            resultJson.put("numPerPage", rows);// 每页数
+            resultJson.put("nextPage", totalPage - page == 0 ? page : page + 1);// 下一页
+            resultJson.put("previousPage", page - 0 == 1 ? page : page - 1);// 上一页
+            resultJson.put("hasPreviousPage", true);// 有上一页
+            resultJson.put("hasNextPage", true);// 有下一页
+            resultJson.put("firstPage", true);// 首页
+            resultJson.put("lastPage", true);// 尾页
+        }
+        ResponseUtil.writeJson(ServletActionContext.getResponse(), resultJson.toString());
+        return null;
+    }
+
+}

+ 37 - 0
QueryUrlEnum.java

@@ -0,0 +1,37 @@
+package com.happy.Model;
+
+public enum QueryUrlEnum {
+
+    ACCOUNT_REGISTER("accountRegister","用户注册"),
+    ACCOUNT_RECHARGE("accountRecharge","账户充值"),
+    ACCOUNT_MODIFY("accountModify","用户信息修改"),
+    ACCOUNT_INFO("queryAccountInfo","账户信息(余额等信息)"),
+    HISTORY_CUMULANT("queryHistoryCumulantInfo","历史记录"),
+    LAST_HISTORY("queryLastHistoryElectricityInfo","最新一条记录"),
+    METER_REAL_INFO("queryRealElectricityInfo","电表实时信息"),
+    POWER_MONTH_BILL("queryMonthlyPowerBillInfo","电费月账单"),
+    QUERY_TOKEN("queryToken","获取token"),
+    REMOTE_DISCONNECT("remoteDisconnect","拉合闸"),
+    USER_INFO("queryUserAccountInfo","用户信息(用户名、联系人、手机等)"),
+    WATER_MONTH_BILL("queryMonthlyWaterBillInfo","水费月账单"),
+    LAST_HISTORY_CUMULANT("queryLastHistoryCumulantInfo","最近一条历史数据"),
+    QUERY_BUILDING_USED("buildingEnergyConsumption/queryBuildingUsed","查询建筑日/小时用量数据"),
+    QUERY_BUILDING("buildingEnergyConsumption/queryBuilding","查询建筑信息"),
+    QUERY_DATACENTER("buildingEnergyConsumption/queryDataCenter","查询数据中心信息"),
+    queryPowerRealTimeData("queryPowerRealTimeData", "查询电表实时数据"),
+    queryChangedUserAccountInfo("queryChangedUserAccountInfo", "查询用户信息"),
+    queryEnergyUnitUsed("queryEnergyUnitUsed", "查询用能单位能耗")
+    ;
+
+    String url;
+    String dsc;
+
+    QueryUrlEnum(String url, String dsc) {
+        this.url = url;
+        this.dsc = dsc;
+    }
+
+    public String getUrl() {
+        return url;
+    }
+}

+ 124 - 0
Recharge.java

@@ -0,0 +1,124 @@
+package com.happy.Model;
+
+import java.math.BigDecimal;
+
+public class Recharge {
+
+    public int id;
+    public String order_num;
+    public String card_number;
+    public String user_name;
+    public double account;
+    public String re_time;
+    public int state;
+    public String stu_number;
+    public String school;
+    public String build;
+    public String room;
+    public Integer pay_state;
+    public String handler_state;
+
+    public String getStu_number() {
+        return stu_number;
+    }
+
+    public void setStu_number(String stu_number) {
+        this.stu_number = stu_number;
+    }
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getOrder_num() {
+        return order_num;
+    }
+
+    public void setOrder_num(String order_num) {
+        this.order_num = order_num;
+    }
+
+    public String getCard_number() {
+        return card_number;
+    }
+
+    public void setCard_number(String card_number) {
+        this.card_number = card_number;
+    }
+
+    public String getUser_name() {
+        return user_name;
+    }
+
+    public void setUser_name(String user_name) {
+        this.user_name = user_name;
+    }
+
+    public double getAccount() {
+        return account;
+    }
+
+    public void setAccount(double account) {
+        this.account = account;
+    }
+
+    public String getRe_time() {
+        return re_time;
+    }
+
+    public void setRe_time(String re_time) {
+        this.re_time = re_time;
+    }
+
+    public int getState() {
+        return state;
+    }
+
+    public void setState(int state) {
+        this.state = state;
+    }
+
+    public String getSchool() {
+        return school;
+    }
+
+    public void setSchool(String school) {
+        this.school = school;
+    }
+
+    public String getBuild() {
+        return build;
+    }
+
+    public void setBuild(String build) {
+        this.build = build;
+    }
+
+    public String getRoom() {
+        return room;
+    }
+
+    public void setRoom(String room) {
+        this.room = room;
+    }
+
+    public Integer getPay_state() {
+        return pay_state;
+    }
+
+    public void setPay_state(Integer pay_state) {
+        this.pay_state = pay_state;
+    }
+
+    public String getHandler_state() {
+        return handler_state;
+    }
+
+    public void setHandler_state(String handler_state) {
+        this.handler_state = handler_state;
+    }
+}

+ 31 - 0
RechargeDao.java

@@ -0,0 +1,31 @@
+package com.happy.dao;
+
+
+import com.happy.Model.Recharge;
+import com.happy.Model.Recharge_elc;
+
+import java.util.List;
+
+public interface RechargeDao {
+
+    public List<Recharge> queryByStu(String stu_number, String re_time);
+
+    public int insertRecharge(Recharge recharge);
+
+    public int updatePay(String orderNo);
+
+    public int updateMoney(String orderNo);
+
+    public int insertRecharge2(Recharge_elc recharge);
+
+    public int succRecharge2(String orderNo);
+
+    public int succRecharge3(String orderNo);
+
+    public Recharge findPayByNo(String order_num);
+
+    public Recharge_elc findPayElByNo(String order_num);
+
+    public List<Recharge_elc> queryRecordByStu(String stu_number, String re_time);
+
+}

+ 191 - 0
RechargeDaoImpl.java

@@ -0,0 +1,191 @@
+package com.happy.dao.impl;
+
+import com.happy.Model.Consume;
+import com.happy.Model.Recharge;
+import com.happy.Model.Recharge_elc;
+import com.happy.dao.ConsumeDao;
+import com.happy.dao.RechargeDao;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.jdbc.core.BeanPropertyRowMapper;
+import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
+import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
+import org.springframework.stereotype.Repository;
+
+import java.util.List;
+
+@Repository("RechargeDao")
+public class RechargeDaoImpl implements RechargeDao {
+
+    @Autowired
+    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
+
+    public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
+        return namedParameterJdbcTemplate;
+    }
+
+    public void setNamedParameterJdbcTemplate(
+            NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
+        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
+    }
+
+    public List<Recharge> queryByStu(String stu_number, String re_time){
+        String sql="select * from `recharge` where `pay_state`=2 and stu_number=:stu_number and re_time like '" + re_time + "%' order by id desc";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("stu_number", stu_number);
+        List<Recharge> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Recharge>(Recharge.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public int insertRecharge(Recharge recharge){
+        String sql = "insert into recharge(order_num, card_number, user_name, account, re_time, state, stu_number) values(:order_num, :card_number, :user_name, :account, :re_time, :state, :stu_number)";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("order_num", recharge.getOrder_num());
+        sps.addValue("card_number", recharge.getCard_number());
+        sps.addValue("user_name", recharge.getUser_name());
+        sps.addValue("account", recharge.getAccount());
+        sps.addValue("re_time", recharge.getRe_time());
+        sps.addValue("state", recharge.getState());
+        sps.addValue("stu_number", recharge.getStu_number());
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    // 修改水费为已支付
+    public int updatePay(String orderNo){
+        String sql = "update `recharge` set pay_state=1 where order_num=:order_num";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("order_num", orderNo);
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    // 修改水费为已到账
+    public int updateMoney(String orderNo){
+        String sql = "update `recharge` set pay_state=2 where order_num=:order_num";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("order_num", orderNo);
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    // 插入充值电费记录
+    public int insertRecharge2(Recharge_elc recharge){
+        String sql = "insert into `recharge_elc`(order_num, card_number, user_name, account, re_time, state, stu_number, school, build, room,day_time,pointid) values(:order_num, :card_number, :user_name, :account, :re_time, :state, :stu_number, :school, :build, :room,:day_time,:pointid)";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("order_num", recharge.getOrder_num());
+        sps.addValue("card_number", recharge.getCard_number());
+        sps.addValue("user_name", recharge.getUser_name());
+        sps.addValue("account", recharge.getAccount());
+        sps.addValue("re_time", recharge.getRe_time());
+        sps.addValue("state", recharge.getState());
+        sps.addValue("stu_number", recharge.getStu_number());
+        sps.addValue("school", recharge.getSchool());
+        sps.addValue("build", recharge.getBuild());
+        sps.addValue("room", recharge.getRoom());
+        sps.addValue("day_time", recharge.getDay_time());
+        sps.addValue("pointid", recharge.getPointid());
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    // 修改电费支付状态为已支付
+    public int succRecharge2(String orderNo){
+        String sql = "update `recharge_elc` set state=1 where order_num=:order_num";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("order_num", orderNo);
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    // 修改电费支付状态为已到账
+    public int succRecharge3(String order_num){
+        String sql = "update `recharge_elc` set `state`=2 where order_num=:order_num";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("order_num", order_num);
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    //根据订单号查找支付记录信息
+    public Recharge findPayByNo(String order_num) {
+        String sql = "select * from recharge where `pay_state`=2 and order_num=:order_num";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("order_num", order_num);
+        Recharge recharge = null;
+        try{
+            recharge = namedParameterJdbcTemplate.queryForObject(sql, sps, new BeanPropertyRowMapper<Recharge>(Recharge.class));
+        }
+        catch(Exception e){
+            recharge = null;
+        }
+        return recharge;
+    }
+
+    //根据订单号查找电费支付记录信息,未支付成功
+    public Recharge_elc findPayElByNo(String order_num) {
+        String sql = "select * from recharge_elc where order_num=:order_num ";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("order_num", order_num);
+        Recharge_elc recharge = null;
+        try{
+            recharge = namedParameterJdbcTemplate.queryForObject(sql, sps, new BeanPropertyRowMapper<Recharge_elc>(Recharge_elc.class));
+        }
+        catch(Exception e){
+            recharge = null;
+        }
+        return recharge;
+    }
+
+    public List<Recharge_elc> queryRecordByStu(String stu_number, String re_time){
+        String sql="select * from recharge_elc where `stu_number`=:stu_number and `state`=2 and `re_time` like '"+ re_time +"%' order by id desc";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("stu_number", stu_number);
+        List<Recharge_elc> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Recharge_elc>(Recharge_elc.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+
+
+}

+ 31 - 0
RechargeService.java

@@ -0,0 +1,31 @@
+package com.happy.service;
+
+import com.happy.Model.Recharge;
+import com.happy.Model.Recharge_elc;
+import com.happy.dao.RechargeDao;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+public interface RechargeService {
+
+    public List<Recharge> queryByStu(String stu_number, String re_time);
+
+    public int insertRecharge(Recharge recharge);
+
+    public int updatePay(String orderNo);
+
+    public int updateMoney(String orderNo);
+
+    public int insertRecharge2(Recharge_elc recharge);
+
+    public int succRecharge2(String orderNo);
+
+    public int succRecharge3(String orderNo);
+
+    public Recharge findPayByNo(String order_num);
+
+    public Recharge_elc findPayElByNo(String order_num);
+
+    public List<Recharge_elc> queryRecordByStu(String stu_number, String re_time);
+}

+ 57 - 0
RechargeServiceImpl.java

@@ -0,0 +1,57 @@
+package com.happy.service.impl;
+
+import com.happy.Model.Recharge;
+import com.happy.Model.Recharge_elc;
+import com.happy.dao.RechargeDao;
+import com.happy.service.RechargeService;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+@Service("RechargeService")
+public class RechargeServiceImpl implements RechargeService {
+
+    @Resource
+    public RechargeDao rechargeDao;
+
+    public List<Recharge> queryByStu(String stu_number, String re_time){
+        return rechargeDao.queryByStu(stu_number, re_time);
+    }
+
+    public int insertRecharge(Recharge recharge){
+        return rechargeDao.insertRecharge(recharge);
+    }
+
+    public int updatePay(String orderNo){
+        return rechargeDao.updatePay(orderNo);
+    }
+
+    public int updateMoney(String orderNo){
+        return rechargeDao.updateMoney(orderNo);
+    }
+
+    public int insertRecharge2(Recharge_elc recharge){
+        return rechargeDao.insertRecharge2(recharge);
+    }
+
+    public int succRecharge2(String orderNo){
+        return rechargeDao.succRecharge2(orderNo);
+    }
+
+    public int succRecharge3(String orderNo){
+        return rechargeDao.succRecharge3(orderNo);
+    }
+
+    public Recharge findPayByNo(String order_num){
+        return rechargeDao.findPayByNo(order_num);
+    }
+
+    public Recharge_elc findPayElByNo(String order_num){
+        return rechargeDao.findPayElByNo(order_num);
+    }
+
+    public List<Recharge_elc> queryRecordByStu(String stu_number, String re_time){
+        return rechargeDao.queryRecordByStu(stu_number, re_time);
+    }
+}

+ 131 - 0
Recharge_elc.java

@@ -0,0 +1,131 @@
+package com.happy.Model;
+
+public class Recharge_elc {
+
+    public int id;
+    public String order_num;
+    public String card_number;
+    public String user_name;
+    public double account;
+    public String re_time;
+    public int state;
+    public String stu_number;
+    public String school;
+    public String build;
+    public String room;
+    public String handler_state;
+    public String day_time;
+    public String pointid;
+
+    public String getStu_number() {
+        return stu_number;
+    }
+
+    public void setStu_number(String stu_number) {
+        this.stu_number = stu_number;
+    }
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getOrder_num() {
+        return order_num;
+    }
+
+    public void setOrder_num(String order_num) {
+        this.order_num = order_num;
+    }
+
+    public String getCard_number() {
+        return card_number;
+    }
+
+    public void setCard_number(String card_number) {
+        this.card_number = card_number;
+    }
+
+    public String getUser_name() {
+        return user_name;
+    }
+
+    public void setUser_name(String user_name) {
+        this.user_name = user_name;
+    }
+
+    public double getAccount() {
+        return account;
+    }
+
+    public void setAccount(double account) {
+        this.account = account;
+    }
+
+    public String getRe_time() {
+        return re_time;
+    }
+
+    public void setRe_time(String re_time) {
+        this.re_time = re_time;
+    }
+
+    public int getState() {
+        return state;
+    }
+
+    public void setState(int state) {
+        this.state = state;
+    }
+
+    public String getSchool() {
+        return school;
+    }
+
+    public void setSchool(String school) {
+        this.school = school;
+    }
+
+    public String getBuild() {
+        return build;
+    }
+
+    public void setBuild(String build) {
+        this.build = build;
+    }
+
+    public String getRoom() {
+        return room;
+    }
+
+    public void setRoom(String room) {
+        this.room = room;
+    }
+
+    public String getHandler_state() {
+        return handler_state;
+    }
+
+    public void setHandler_state(String handler_state) {
+        this.handler_state = handler_state;
+    }
+
+    public String getDay_time() {
+        return day_time;
+    }
+
+    public void setDay_time(String day_time) {
+        this.day_time = day_time;
+    }
+
+    public String getPointid() {
+        return pointid;
+    }
+
+    public void setPointid(String pointid) {
+        this.pointid = pointid;
+    }
+}

+ 53 - 0
ResUtil.java

@@ -0,0 +1,53 @@
+package com.happy.Until;
+
+import org.apache.poi.ss.usermodel.Workbook;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+
+public class ResUtil {
+
+	public static void write(Object o, HttpServletResponse response)
+			throws Exception {
+		response.setContentType("text/html;charset=utf-8");
+//		response.setHeader("Access-Control-Allow-Origin", "*");
+		PrintWriter out = response.getWriter();
+		out.println(o.toString());
+		out.flush();
+		out.close();
+	}
+
+	public static void write(String o, HttpServletResponse response)
+			throws Exception {
+		response.setContentType("text/html;charset=utf-8");
+		PrintWriter out = response.getWriter();
+		out.println(o.toString());
+		out.flush();
+		out.close();
+	}
+
+	public static void writeJson(HttpServletResponse respone, String result) {
+		respone.setContentType("application/json;charset=utf-8");
+		PrintWriter out;
+		try {
+			out = respone.getWriter();
+			out.print(result);
+			out.flush();
+			out.close();
+		} catch (Exception e) { 
+			// //System.out.println("Comm_Util_writeJson---->" + e);
+		}
+	}
+
+	public static void export(HttpServletResponse response, Workbook wb,
+			String fileName) throws Exception {
+		response.setHeader("Content-Disposition", "attachment;filename="
+				+ new String(fileName.getBytes("utf-8"), "iso8859-1"));
+		response.setContentType("application/ynd.ms-excel;charset=UTF-8");
+		OutputStream out = response.getOutputStream();
+		wb.write(out);
+		out.flush();
+		out.close();
+	}
+}

+ 52 - 0
ResponseUtil.java

@@ -0,0 +1,52 @@
+package com.happy.Until;
+
+import org.apache.poi.ss.usermodel.Workbook;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+
+public class ResponseUtil {
+
+	public static void write(Object o, HttpServletResponse response)
+			throws Exception {
+		response.setContentType("text/html;charset=utf-8");
+		PrintWriter out = response.getWriter();
+		out.println(o.toString());
+		out.flush();
+		out.close();
+	}
+
+	public static void write(String o, HttpServletResponse response)
+			throws Exception {
+		response.setContentType("text/html;charset=utf-8");
+		PrintWriter out = response.getWriter();
+		out.println(o.toString());
+		out.flush();
+		out.close();
+	}
+
+	public static void writeJson(HttpServletResponse respone, String result) {
+		respone.setContentType("application/json;charset=utf-8");
+		PrintWriter out;
+		try {
+			out = respone.getWriter();
+			out.print(result);
+			out.flush();
+			out.close();
+		} catch (Exception e) {
+			// //System.out.println("Comm_Util_writeJson---->" + e);
+		}
+	}
+
+	public static void export(HttpServletResponse response, Workbook wb,
+			String fileName) throws Exception {
+		response.setHeader("Content-Disposition", "attachment;filename="
+				+ new String(fileName.getBytes("utf-8"), "iso8859-1"));
+		response.setContentType("application/ynd.ms-excel;charset=UTF-8");
+		OutputStream out = response.getOutputStream();
+		wb.write(out);
+		out.flush();
+		out.close();
+	}
+}

+ 86 - 0
ResultStatusCode.java

@@ -0,0 +1,86 @@
+package com.happy.constant;
+
+public enum ResultStatusCode {
+	/** OKlockcslock */
+	QUIT(200, "退出成功"),
+	/** OK */
+	OK(200, "OK"),
+	/** 访问超时 */
+	TIME_OUT(130, "访问超时"),
+	/** 参数解析失败 */
+	BAD_REQUEST(400, "参数解析失败"),
+	/** 记录不存在 */
+	NOT_EXIST(404, "记录不存在"),
+	/** 不支持当前请求方法 */
+	METHOD_NOT_ALLOWED(405, "不支持当前请求方法"),
+	/** 服务器运行异常 */
+	SYSTEM_ERR(500, "服务器运行异常"),
+	/** 该用户不存在或密码错误 */
+	NOT_EXIST_USER_OR_ERROR_PWD(10000, "该用户不存在或账号密码错误"),
+	/** 该用户已登录 */
+	LOGINED_IN(10001, "该用户已登录"),
+	LOGINED_IN2(10002, "该用户不存在"),
+	LOGINED_IN3(100021, "该用户登录已失效"),
+	/** 登录异常 */
+	SHIRO_ERROR(10003, "登录异常"),
+	/** 您没有该权限 */
+	UNAUTHO_ERROR(10004, "您没有该权限"),
+	/** 请绑定手机号 */
+	BIND_PHONE(10010, "请绑定手机号"),
+	/** 上传文件异常 */
+	UPLOAD_ERROR(20000, "上传文件异常"),
+	/** 无效的验证码 */
+	INVALID_CAPTCHA(30005, "无效的验证码"),
+	/** 该用户已被冻结 */
+	USER_FROZEN(40000, "该用户已被冻结"),
+	/** 该用户未绑定微信号 */
+	USER_NOT_WX_OAUTH(40004, "该用户未进行微信授权"),
+    /** 该用户未绑定微信号 */
+	USER_NOT_BIND_WX(5000, "该用户未绑定微信号"),
+    /** 该用户成功绑定微信号 */
+    USER_BIND_WX_OK(5005, "该用户成功绑定微信号"),
+	/** 该部门已存在 */
+	DEPARTMENT_EXIT(5006, "该部门已存在"),
+	/** 该用户已存在 */
+	USER_EXIST(6000, "该用户已存在"),
+	/** 该账号已存在 */
+	USERACCOUNT_EXIST(6002, "该账号已存在"),
+	/** 缴费用户信息不存在 */
+	PARTYDUES_USER_NOEXIT(6003, "缴费用户信息不存在"),
+	/** 党费信息不存在 */
+	PARTYDUES_NOEXIT(6004, "费用信息不存在"),
+	/** 党费信息党费已支付 */
+	PARTYDUES_OK(6005, "费用已支付"),
+	/** 党费订单支付失败 */
+	PARTYDUES_ERR(6009, "费用支付失败");
+
+	private int status;
+	private String msg;
+
+	public int getStatus() {
+		return status;
+	}
+
+	public void setStatus(int status) {
+		this.status = status;
+	}
+
+	public String getMsg() {
+		return msg;
+	}
+
+	public void setMsg(String msg) {
+		this.msg = msg;
+	}
+
+	private ResultStatusCode(int code, String msg) {
+		this.status = code;
+		this.msg = msg;
+	}
+
+	@Override
+	public String toString() {
+		return "{\"status\":" + this.status + ",\"msg\":\"" + this.msg + "\",\"data\": null, \"ok\": false}";
+	}
+}
+

+ 103 - 0
ResultUtil.java

@@ -0,0 +1,103 @@
+package com.happy.Until;
+
+import com.happy.constant.ResultStatusCode;
+
+/**
+ * @author yp
+ * @date 2019/10/31 0:02
+ */
+public class ResultUtil {
+    private static final long serialVersionUID = 1L;
+    // 响应状态
+    protected Integer status = 0;
+
+    // 响应消息
+    protected String msg;
+
+    // 响应数据
+    protected Object data;
+
+    public static ResultUtil buildOK() {
+        return new ResultUtil(ResultStatusCode.OK);
+    }
+
+    public static ResultUtil buildOK(Object data) {
+        return ResultUtil.build(ResultStatusCode.OK, data);
+    }
+
+    public static ResultUtil build(ResultStatusCode rsc) {
+        return new ResultUtil(rsc.getStatus(), rsc.getMsg(), null);
+    }
+
+    public static ResultUtil build(ResultStatusCode rsc, Object data) {
+        return new ResultUtil(rsc.getStatus(), rsc.getMsg(), data);
+    }
+
+    public static ResultUtil build(Integer status, String msg, Object data) {
+        return new ResultUtil(status, msg, data);
+    }
+
+    public static ResultUtil ok(Object data) {
+        return new ResultUtil(data);
+    }
+
+    public static ResultUtil ok() {
+        return new ResultUtil(null);
+    }
+
+    public ResultUtil() {
+
+    }
+
+    public static ResultUtil build(Integer status, String msg) {
+        return new ResultUtil(status, msg, null);
+    }
+
+    public ResultUtil(Integer status, String msg, Object data) {
+        this.status = status;
+        this.msg = msg;
+        this.data = data;
+    }
+
+    public ResultUtil(Object data) {
+        this.status = 200;
+        this.msg = "OK";
+        this.data = data;
+    }
+
+    public Boolean isOK() {
+        if (null == this.status) {
+            return false;
+        }
+        return this.status == 200;
+    }
+
+    public Integer getStatus() {
+        return status;
+    }
+
+    public void setStatus(Integer status) {
+        this.status = status;
+    }
+
+    public String getMsg() {
+        return msg;
+    }
+
+    public void setMsg(String msg) {
+        this.msg = msg;
+    }
+
+    public Object getData() {
+        return data;
+    }
+
+    public void setData(Object data) {
+        this.data = data;
+    }
+
+    @Override
+    public String toString() {
+        return "ResultUtil [status=" + status + ", msg=" + msg + ", data=" + data + "]";
+    }
+}

+ 42 - 0
SHA1.java

@@ -0,0 +1,42 @@
+package com.happy.Unitil_nsh;
+import java.security.MessageDigest;
+
+/**
+ * 微信SHA1算法
+ * @author lujunjie
+ * @date   2018/03/01
+ */
+public final class SHA1 {
+
+    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
+
+    /**
+     *  将字节并格式化
+     * @param bytes 原始字节
+     * @return 格式化字节
+     */
+    private static String getFormattedText(byte[] bytes) {
+        int len = bytes.length;
+        StringBuilder buf = new StringBuilder(len * 2);
+        // 把密文转换成十六进制的字符串形式
+        for (int j = 0; j < len; j++) {
+            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
+            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
+        }
+        return buf.toString();
+    }
+
+    public static String encode(String str) {
+        if (str == null) {
+            return null;
+        }
+        try {
+            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
+            messageDigest.update(str.getBytes());
+            return getFormattedText(messageDigest.digest());
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+}

+ 845 - 0
StringUtil.java

@@ -0,0 +1,845 @@
+package com.happy.Unitil_elc;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.math.NumberUtils;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.text.BreakIterator;
+import java.text.DecimalFormat;
+import java.util.*;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+
+public class StringUtil {
+
+    /** 空字符串。 */
+    public static final String   EMPTY_STRING        = "";
+
+    private static final char    QUOTE_ENCODE[]      = "&quot;".toCharArray();
+    private static final char    AMP_ENCODE[]        = "&amp;".toCharArray();
+    private static final char    LT_ENCODE[]         = "&lt;".toCharArray();
+    private static final char    GT_ENCODE[]         = "&gt;".toCharArray();
+    private static final int     DUMP_HEX_CHAR_COUNT = 75;
+    private static MessageDigest digest              = null;
+    // private static final int fillchar = 61;
+    private static Random        randGen             = new Random();
+    private static char          numbersAndLetters[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
+    private static final char    zeroArray[]         = "0000000000000000".toCharArray();
+    private static final char[]  base64Chars         = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
+    private static final char[]  upcaseHexChar       = "0123456789ABCDEF".toCharArray();
+    private static final char[]  lowerHexChar        = "0123456789abcdef".toCharArray();
+
+    private static int[]         hexCharCodes        = new int[256];
+
+    private static int[]         base64Codes         = new int[256];
+    static {
+        for (int i = 0; i < 256; i++)
+            hexCharCodes[i] = base64Codes[i] = -1;
+        for (int i = 0; i < base64Chars.length; i++)
+            base64Codes[base64Chars[i]] = (byte) i;
+        for (int i = 0; i < upcaseHexChar.length; i++)
+            hexCharCodes[upcaseHexChar[i]] = (byte) i;
+        for (int i = 0; i < lowerHexChar.length; i++)
+            hexCharCodes[lowerHexChar[i]] = (byte) i;
+    }
+
+    /**
+     * 如果字符串是<code>null</code>,则返回指定默认字符串,否则返回字符串本身。
+     * 
+     * <pre>
+     * StringUtil.defaultIfNull(null, &quot;default&quot;)  = &quot;default&quot;
+     * StringUtil.defaultIfNull(&quot;&quot;, &quot;default&quot;)    = &quot;&quot;
+     * StringUtil.defaultIfNull(&quot;  &quot;, &quot;default&quot;)  = &quot;  &quot;
+     * StringUtil.defaultIfNull(&quot;bat&quot;, &quot;default&quot;) = &quot;bat&quot;
+     * </pre>
+     * 
+     * @param str 要转换的字符串
+     * @param defaultStr 默认字符串
+     * @return 字符串本身或指定的默认字符串
+     */
+    public static String defaultIfNull(String str, String defaultStr) {
+        return (str == null) ? defaultStr : str;
+    }
+
+    public static boolean isDigits(String str) {
+        if ((str == null) || (str.length() == 0)) {
+            return false;
+        }
+        for (int i = 0; i < str.length(); i++) {
+            if (!Character.isDigit(str.charAt(i))) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    public static boolean isDigits(Object obj) {
+        if (obj == null) return false;
+        String str = obj.toString();
+        return isDigits(str);
+    }
+
+    public static final String escapeHTMLTags(String in) {
+        if (in == null) return null;
+        int i = 0;
+        int last = 0;
+        char input[] = in.toCharArray();
+        int len = input.length;
+        StringBuffer out = new StringBuffer((int) ((double) len * 1.3D));
+        for (; i < len; i++) {
+            char ch = input[i];
+            if (ch > '>') continue;
+            if (ch == '<') {
+                if (i > last) out.append(input, last, i - last);
+                last = i + 1;
+                out.append(LT_ENCODE);
+                continue;
+            }
+            if (ch != '>') continue;
+            if (i > last) out.append(input, last, i - last);
+            last = i + 1;
+            out.append(GT_ENCODE);
+        }
+
+        if (last == 0) return in;
+        if (i > last) out.append(input, last, i - last);
+        return out.toString();
+    }
+
+    public static final synchronized String hash(String data) {
+        if (digest == null) try {
+            digest = MessageDigest.getInstance("MD5");
+        } catch (NoSuchAlgorithmException nsae) {
+            System.err.println("Failed to load the MD5 MessageDigest. We will be unable to function normally.");
+            nsae.printStackTrace();
+        }
+        digest.update(data.getBytes());
+        return encodeHex(digest.digest());
+    }
+
+    public static final String encodeHex(byte bytes[]) {
+        char[] buf = new char[bytes.length * 2];
+        for (int i = 0; i < bytes.length; i++) {
+            int code = bytes[i] & 0xff;
+            buf[2 * i] = upcaseHexChar[code >> 4];
+            buf[2 * i + 1] = upcaseHexChar[code & 0xf];
+        }
+        return new String(buf);
+    }
+
+    public static final String dumpHex(byte bytes[]) {
+        int bytepos, bufpos, linecount = (bytes.length + 15) / 16;
+        char[] buf = new char[linecount * DUMP_HEX_CHAR_COUNT];
+        byte[] bs = new byte[16];
+
+        bytepos = 0;
+        for (int i = 0; i < linecount; i++) {
+            int addr = i * 16;
+            bufpos = i * DUMP_HEX_CHAR_COUNT;
+            buf[bufpos++] = upcaseHexChar[(addr >> 12) & 0xf];
+            buf[bufpos++] = upcaseHexChar[(addr >> 8) & 0xf];
+            buf[bufpos++] = upcaseHexChar[(addr >> 4) & 0xf];
+            buf[bufpos++] = upcaseHexChar[(addr) & 0xf];
+            buf[bufpos++] = ' ';
+            buf[bufpos++] = ' ';
+            for (int j = 0; j < 16; j++, bytepos++) {
+                if (bytepos < bytes.length) {
+                    int code = bytes[bytepos] & 0xff;
+                    bs[j] = bytes[bytepos];
+                    buf[bufpos++] = upcaseHexChar[code >> 4];
+                    buf[bufpos++] = upcaseHexChar[code & 0xf];
+                    if (j == 7) buf[bufpos++] = '-';
+                    else buf[bufpos++] = ' ';
+                } else {
+                    buf[bufpos++] = ' ';
+                    buf[bufpos++] = ' ';
+                    buf[bufpos++] = ' ';
+                    bs[j] = ' ';
+                }
+            }
+            buf[bufpos++] = ' ';
+            buf[bufpos++] = ' ';
+            char[] chs = new String(bs).toCharArray();
+            for (int k = 0; k < chs.length; k++) {
+                char ch = chs[k];
+                if ((ch > '\0') && (ch < ' ')) buf[bufpos++] = '.';
+                else buf[bufpos++] = ch;
+
+            }
+            int endLine = (i + 1) * DUMP_HEX_CHAR_COUNT - 2;
+            for (; bufpos < endLine; bufpos++)
+                buf[bufpos] = ' ';
+            buf[bufpos++] = '\r';
+            buf[bufpos++] = '\n';
+        }
+        return new String(buf);
+    }
+
+    public static final byte[] decodeHex(String hex) {
+        char chars[] = hex.toCharArray();
+        byte bytes[] = new byte[chars.length / 2];
+        int byteCount = 0;
+        for (int i = 0; i < chars.length; i += 2) {
+            byte newByte = 0;
+            newByte |= hexCharCodes[chars[i]];
+            newByte <<= 4;
+            newByte |= hexCharCodes[chars[i + 1]];
+            bytes[byteCount] = newByte;
+            byteCount++;
+        }
+
+        return bytes;
+    }
+
+    public static String encodeBase64(String data) {
+        return encodeBase64(data.getBytes());
+    }
+
+    public static String encodeBase64(byte data[]) {
+        int len = data.length;
+        StringBuffer ret = new StringBuffer((len / 3 + 1) * 4);
+        for (int i = 0; i < len; i++) {
+            int c = data[i] >> 2 & 0x3f;
+            ret.append(base64Chars[c]);
+            c = data[i] << 4 & 0x3f;
+            if (++i < len) c |= data[i] >> 4 & 0xf;
+            ret.append(base64Chars[c]);
+            if (i < len) {
+                c = data[i] << 2 & 0x3f;
+                if (++i < len) c |= data[i] >> 6 & 3;
+                ret.append(base64Chars[c]);
+            } else {
+                i++;
+                ret.append('=');
+            }
+            if (i < len) {
+                c = data[i] & 0x3f;
+                ret.append(base64Chars[c]);
+            } else {
+                ret.append('=');
+            }
+        }
+
+        return ret.toString();
+    }
+
+    public static byte[] decodeBase64(String data) {
+        int len = data.length();
+        byte[] result = new byte[((len * 3) / 4)];
+        int pos = 0;
+        for (int i = 0; i < len; i++) {
+
+            int c = base64Codes[data.charAt(i)];
+            i++;
+            int c1 = base64Codes[data.charAt(i)];
+            c = c << 2 | c1 >> 4 & 3;
+            result[pos++] = (byte) c;
+            if (++i < len) {
+                c = data.charAt(i);
+                if (61 == c) break;
+                c = base64Codes[data.charAt(i)];
+                c1 = c1 << 4 & 0xf0 | c >> 2 & 0xf;
+                result[pos++] = (byte) c1;
+            }
+            if (++i >= len) continue;
+            c1 = data.charAt(i);
+            if (61 == c1) break;
+            c1 = base64Codes[data.charAt(i)];
+            c = c << 6 & 0xc0 | c1;
+            result[pos++] = (byte) c;
+        }
+        if (result.length != pos) {
+            byte[] result2 = new byte[pos];
+            System.arraycopy(result, 0, result2, 0, pos);
+            result = result2;
+        }
+        return result;
+    }
+
+    public static final String[] toLowerCaseWordArray(String text) {
+        if (text == null || text.length() == 0) return new String[0];
+        List<String> wordList = new ArrayList<String>();
+        BreakIterator boundary = BreakIterator.getWordInstance();
+        boundary.setText(text);
+        int start = 0;
+        for (int end = boundary.next(); end != -1; end = boundary.next()) {
+            String tmp = text.substring(start, end).trim();
+            tmp = tmp.replace("+", "");
+            tmp = tmp.replace("/", "");
+            tmp = tmp.replace("\\", "");
+            tmp = tmp.replace("#", "");
+            tmp = tmp.replace("*", "");
+            tmp = tmp.replace(")", "");
+            tmp = tmp.replace("(", "");
+            tmp = tmp.replace("&", "");
+            if (tmp.length() > 0) wordList.add(tmp);
+            start = end;
+        }
+
+        return (String[]) (String[]) wordList.toArray(new String[wordList.size()]);
+    }
+
+    public static final String createTempTable() {
+        return "temp_" + StringUtil.randomString(10);
+    }
+
+    /**
+     * 产生指定长度的字符串
+     * 
+     * @param length
+     * @return
+     */
+    public static final String randomString(int length) {
+        if (length < 1) {
+            return null;
+        }
+
+        char randBuffer[] = new char[length];
+        for (int i = 0; i < randBuffer.length; i++)
+            randBuffer[i] = numbersAndLetters[randGen.nextInt(numbersAndLetters.length)];
+
+        return new String(randBuffer);
+    }
+
+    public static final String randomNumber(int length) {
+        Long value = Math.abs(randGen.nextLong());
+        String strValue = value.toString();
+        if (strValue.length() > length) {
+            strValue = strValue.substring(0, length);
+        }
+
+        return strValue;
+    }
+
+    public static final String chopAtWord(String string, int length) {
+        if (string == null) return string;
+        char charArray[] = string.toCharArray();
+        int sLength = string.length();
+        if (length < sLength) sLength = length;
+        for (int i = 0; i < sLength - 1; i++) {
+            if (charArray[i] == '\r' && charArray[i + 1] == '\n') return string.substring(0, i + 1);
+            if (charArray[i] == '\n') return string.substring(0, i);
+        }
+
+        if (charArray[sLength - 1] == '\n') return string.substring(0, sLength - 1);
+        if (string.length() < length) return string;
+        for (int i = length - 1; i > 0; i--)
+            if (charArray[i] == ' ') return string.substring(0, i).trim();
+
+        return string.substring(0, length);
+    }
+
+    public static final String escapeForXML(String string) {
+        if (string == null) return null;
+        int i = 0;
+        int last = 0;
+        char input[] = string.toCharArray();
+        int len = input.length;
+        StringBuffer out = new StringBuffer((int) ((double) len * 1.3D));
+        for (; i < len; i++) {
+            char ch = input[i];
+            if (ch > '>') continue;
+            if (ch == '<') {
+                if (i > last) out.append(input, last, i - last);
+                last = i + 1;
+                out.append(LT_ENCODE);
+                continue;
+            }
+            if (ch == '&') {
+                if (i > last) out.append(input, last, i - last);
+                last = i + 1;
+                out.append(AMP_ENCODE);
+                continue;
+            }
+            if (ch != '"') continue;
+            if (i > last) out.append(input, last, i - last);
+            last = i + 1;
+            out.append(QUOTE_ENCODE);
+        }
+
+        if (last == 0) return string;
+        if (i > last) out.append(input, last, i - last);
+        return out.toString();
+    }
+
+    public static final String unescapeFromXML(String string) {
+        string = string.replace("&lt;", "<");
+        string = string.replace("&gt;", ">");
+        string = string.replace("&quot;", "\"");
+        return string.replace("&amp;", "&");
+    }
+
+    public static final String zeroPadString(String string, int length) {
+        if (string == null || string.length() > length) {
+            return string;
+        } else {
+            StringBuffer buf = new StringBuffer(length);
+            buf.append(zeroArray, 0, length - string.length()).append(string);
+            return buf.toString();
+        }
+    }
+
+    public static final String zeroAppendString(String string, int length) {
+        if (string == null || string.length() > length) {
+            return string;
+        } else {
+            StringBuffer buf = new StringBuffer(length);
+            buf.append(string).append(zeroArray, 0, length - string.length());
+            return buf.toString();
+        }
+    }
+
+    public static final String charPadString(String string, int length, char append) {
+        if (string == null || string.length() > length) {
+            return string;
+        } else {
+            char[] charArray = new char[length - string.length()];
+            for (int i = 0; i < charArray.length; i++) {
+                charArray[i] = append;
+            }
+            StringBuffer buf = new StringBuffer(length);
+            buf.append(charArray, 0, charArray.length).append(string);
+            return buf.toString();
+        }
+    }
+
+    public static final String charAppendString(String string, int length, char append) {
+        if (string == null || string.length() > length) {
+            return string;
+        } else {
+            char[] charArray = new char[length - string.length()];
+            for (int i = 0; i < charArray.length; i++) {
+                charArray[i] = append;
+            }
+            StringBuffer buf = new StringBuffer(length);
+            buf.append(string).append(charArray, 0, charArray.length);
+            return buf.toString();
+        }
+    }
+
+    public static final String dateToMillis(Date date) {
+        return zeroPadString(Long.toString(date.getTime()), 15);
+    }
+
+    public static final String collectionToString(Collection<Object> c, String split) {
+        StringBuilder ret = new StringBuilder();
+        List<Object> a;
+        if (c == null) return null;
+        if (split == null) return null;
+        a = new ArrayList<Object>(c);
+        try {
+            for (int i = 0; i < a.size(); i++) {
+                String t = (String) a.get(i);
+                if (i == a.size() - 1) {
+                    ret.append(t);
+                } else {
+                    ret.append(t).append(split);
+
+                }
+            }
+
+            return ret.toString();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+        return null;
+    }
+
+    public static String encodeUrlString(String str) {
+        String strret = null;
+        if (str == null) return str;
+        try {
+            strret = URLEncoder.encode(str, "GBK");
+        } catch (Exception e) {
+            e.printStackTrace(System.err);
+            return null;
+        }
+        return strret;
+    }
+
+    public static String decodeUrlString(String str) {
+        String strret = null;
+        if (str == null) return str;
+        try {
+            strret = URLDecoder.decode(str, "GBK");
+        } catch (Exception e) {
+            e.printStackTrace(System.err);
+            return null;
+        }
+        return strret;
+    }
+
+    public static String join(Object list[], String separator) {
+        int listSize = list.length;
+        int bufSize = listSize == 0 ? 0 : (list[0].toString().length() + separator.length()) * listSize;
+        StringBuffer buf = new StringBuffer(bufSize);
+        for (int i = 0; i < listSize; i++) {
+            if (i > 0) buf.append(separator);
+            buf.append(list[i]);
+        }
+
+        return buf.toString();
+    }
+
+    public static String join(Iterator<?> iterator, String separator) {
+        StringBuffer buf = new StringBuffer();
+        do {
+            if (!iterator.hasNext()) break;
+            buf.append(iterator.next());
+            if (iterator.hasNext()) buf.append(separator);
+        } while (true);
+        return buf.toString();
+    }
+
+    public static boolean isEmpty(String param) {
+        return param == null || "".equals(param) || "".equals(param.trim()) || "null".equals(param) || "\"null\"".equals(param) || "undefined".equals(param) || "[]".equals(param);
+    }
+
+    public static boolean isNotEmpty(String param) {
+        return !isEmpty(param);
+    }
+
+    public static int getDecimalplace(String factor) {
+        int pointPos = factor.indexOf(".");
+        int onePos = factor.indexOf("1");
+        int precision = onePos - pointPos;
+        return precision > 0 ? precision : 0;
+    }
+
+    /**
+     * 对字符串做定长处理,超过长度,截取,长度不够补在前方补齐
+     * 
+     * @param str
+     * @param len
+     * @param appendStr 补齐的字符,
+     * @return
+     */
+    public static String AddjustLength(String str, int len, String appendStr) {
+        if (str == null) {
+            return null;
+        }
+        if (str.length() == len) {
+            return str;
+        } else if (str.length() < len) {
+            StringBuffer buf = new StringBuffer(len);
+            for (int i = 0; i < len - str.length(); i++) {
+                buf.append(appendStr);
+            }
+            buf.append(str);
+            if (buf.length() > len) {
+                return buf.substring(buf.length() - len);
+            } else {
+                return buf.toString();
+            }
+        } else {
+            return str.substring(str.length() - len, str.length());
+        }
+    }
+
+    /**
+     * 比较separator分隔的2个字符串是否相等
+     * 
+     * @param str1
+     * @param str2
+     * @param separator 字符串分隔符
+     * @return
+     */
+    public static boolean isEquals(String str1, String str2, String separator) {
+        if (StringUtils.isEmpty(str1) && StringUtils.isEmpty(str2)) {
+            return false;
+        }
+        String[] str1Array = StringUtils.split(str1, separator);
+        String[] str2Array = StringUtils.split(str2, separator);
+
+        if (str1Array.length != str2Array.length) {
+            return false;
+        }
+
+        List<String> refList = new ArrayList<String>();
+        for (String refStr : str1Array) {
+            refList.add(refStr);
+        }
+
+        for (String desStr : str2Array) {
+            if (!refList.contains(desStr)) {
+                return false;
+            }
+        }
+
+        return true;
+    }
+
+    /**
+     * 转换字符串分隔的字符串为Integer数组
+     * 
+     * @param values
+     * @param spare
+     * @return
+     */
+    public static List<Integer> parseIntList(String values, String spare) {
+        List<Integer> list = new ArrayList<Integer>();
+        String[] valueArray = StringUtils.split(values, spare);
+        if (valueArray != null) {
+            for (String value : valueArray) {
+                if (NumberUtils.isDigits(value)) {
+                    list.add(NumberUtils.toInt(value));
+                }
+            }
+        }
+        return list;
+
+    }
+
+    public static double parseDouble(String src) {
+        if (!isEmpty(src)) {
+            return Double.parseDouble(src);
+        }
+        return 0;
+    }
+
+    public static int parseInt(String src) {
+        if (!isEmpty(src)) {
+            return Integer.parseInt(src);
+        }
+        return 0;
+    }
+
+    public static long parseLong(String src) {
+        if (!isEmpty(src)) {
+            return Long.parseLong(src);
+        }
+        return 0;
+    }
+
+    public static String format(String number, int decimalDigits) {
+        if (!StringUtil.isEmpty(number) && NumberUtils.isDigits(number)) {
+            return StringUtil.format(Double.parseDouble(number), decimalDigits);
+        } else {
+            return number;
+        }
+    }
+
+    public static String trim(String src) {
+        return src == null ? "" : src.trim();
+    }
+
+    /**
+     * 数字格式化函数
+     * 
+     * @param number : 格式化前的数字;
+     * @param decimalDigits : 小数位数;
+     * @return: 字符串;
+     */
+    public static String format(double number, int decimalDigits) {
+        if (number == 0d) {
+            number = 0d;
+        }
+
+        boolean flag = false;
+        if (decimalDigits < 0) {
+            // 小数位数不能小于0.
+            return "";
+        }
+
+        String pattern = "##################";
+        if (decimalDigits > 0) {
+            flag = true;
+            pattern += ".";
+            for (int i = 0; i < decimalDigits; i++) {
+                pattern += "0";
+            }
+        }
+
+        DecimalFormat df = new DecimalFormat(pattern);
+        if (number <= -1d) {
+            return df.format(number);
+        } else if (number > -1d && number < 0d) {
+            return "-0" + df.format(number).substring(1);
+        } else if (number >= 0d && number < 1d) {
+            if (flag) {
+                String temp = df.format(number);
+                if (StringUtil.isNotEmpty(temp) && temp.substring(0, 1).equals(".")) {
+                    return "0" + df.format(number);
+                } else {
+                    return temp;
+                }
+            } else {
+                return df.format(number);
+            }
+        } else {
+            return df.format(number);
+        }
+    }
+
+    public static Integer toInteger(Object object) {
+        if (object == null) {
+            return 0;
+        }
+        return Integer.valueOf(object.toString());
+    }
+
+    public static Short toShort(Object object) {
+        if (object == null) {
+            return null;
+        }
+        return Short.valueOf(object.toString());
+    }
+
+    public static String objectToString(Object obj) {
+        if (obj == null) {
+            return null;
+        } else {
+            return obj.toString();
+        }
+    }
+
+    /**
+     * 字串逆排
+     * 
+     * @return
+     */
+    public static String revert(String src) {
+        if (isEmpty(src)) return "";
+        StringBuffer result = new StringBuffer();
+        for (int i = src.length() - 1; i >= 0; i--) {
+            result.append(src.charAt(i));
+        }
+        return result.toString();
+    }
+
+    public static boolean isValidateString(String path) {
+        if (StringUtil.isEmpty(path)) {
+            return false;
+        } else {
+            return true;
+        }
+    }
+
+    public static String encodingUtf8(String src) throws UnsupportedEncodingException {
+        if (isEmpty(src)) return "";
+        return new String(src.getBytes("ISO-8859-1"), "UTF-8");
+    }
+
+    public static String encodingJson(String src) throws UnsupportedEncodingException {
+        if (isEmpty(src)) return "";
+        int pos = src.indexOf("\\u");
+        StringBuffer sb = new StringBuffer();
+        while (pos >= 0 && (pos + 6 <= src.length())) {
+            sb.append(src.substring(0, pos));
+            String temp = src.substring(pos + 2, pos + 6);
+            sb.append((char) Integer.parseInt(temp, 16));// 将\u6d4b\u8bd5
+                                                         // 格式的文字转为
+                                                         // 正常的string编码
+                                                         // “测试”(因为Ext.encode(array)的方法解析出来是jsonarray格式)
+            src = src.substring(pos + 6);
+            pos = src.indexOf("\\u");
+        }
+        sb.append(src);
+        return sb.toString();
+    }
+
+    /**
+     * 正则
+     */
+    public static String replaceBlank(String str) {
+        String dest = "";
+        if (str != null) {
+            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
+            Matcher m = p.matcher(str);
+            dest = m.replaceAll("");
+        }
+        return dest;
+    }
+
+    /**
+     * 不定参数校验空
+     * 
+     * @param args
+     * @return
+     */
+    public static boolean isNull(String... args) {
+        for (String arg : args) {
+            if (StringUtils.isEmpty(arg)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * 不定参数校验数字
+     * 
+     * @param args
+     * @return
+     */
+    public static boolean isNotNumber(String... args) {
+        for (String arg : args) {
+            if (!NumberUtils.isDigits(arg)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * 不定参数校验数字
+     * 
+     * @param args
+     * @return
+     */
+    public static boolean isNotDigits(String... args) {
+        for (String arg : args) {
+            if (!NumberUtils.isDigits(arg)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * toString增加判空
+     */
+    public static String toString(Object obj) {
+        if(obj == null) {
+            return "";
+        }
+        return obj.toString();
+    }
+
+    /**
+     * @param value:十进制字字符
+     * @param radix:目标进制
+     * @param length:目标长度
+     * @param pad:前补的字符
+     * @return
+     */
+    public static String numStr2PadString(String value, int radix, int length, String pad) {
+        if (value == null) return charPad("", length, pad);
+        // Integer temp = NumberUtils.toInt(value);
+        String result = Integer.toString(NumberUtils.toInt(value), radix);
+        return AddjustLength(result, length, pad);
+    }
+
+    public static String charPad(String value, int length, String pad) {
+        if (value == null || value.length() > length) return value;
+        String padString = "";
+        for (int i = 0; i < (length - value.length()); i++) {
+            padString += pad;
+        }
+        return padString + value;
+    }
+
+    public static void main(String[] args) {
+        System.out.println("operator_secret: " + randomString(17));
+        System.out.println("data_secret: " + randomString(16));
+        System.out.println("data_secret_iv: " + randomString(16));
+        System.out.println("sign_secret: " + randomString(19));
+
+    }
+}

+ 272 - 0
TLinx2Util.java

@@ -0,0 +1,272 @@
+package com.happy.Unitil_nsh;
+
+//~--- non-JDK imports --------------------------------------------------------
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+//~--- JDK imports ------------------------------------------------------------
+
+//~--- classes ----------------------------------------------------------------
+
+/**
+ * Class TLinx2Util
+ * Description
+ * Create 2017-03-07 14:01:23
+ *
+ * @author Benny.YEE
+ */
+public class TLinx2Util {
+
+
+    /**
+     * 签名
+     *
+     * @param postMap
+     * @return
+     */
+    public static String sign(Map<String, String> postMap) {
+        String sign = null;
+
+        try {
+
+            /**
+             * 1 A~z排序(加上open_key)
+             */
+            String sortStr = sort(postMap);
+            System.out.println("====排序后的待签名字符串= " + sortStr);
+            /**
+             * 2 sha1加密(小写)
+             */
+            String sha1 = com.happy.Unitil_nsh.TLinxSHA1.SHA1(sortStr).toLowerCase();
+            System.out.println("====sha1加密后的待签名字符串= " + sha1);
+            /**
+             * 3 md5加密(小写)
+             */
+            sign = com.happy.Unitil_nsh.TLinxMD5.MD5Encode(sha1).toLowerCase();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+        return sign;
+    }
+
+    /**
+     * 验签
+     *
+     * @param respObject
+     * @return
+     */
+    public static Boolean verifySign(JSONObject respObject) {
+        String respSign = respObject.get("sign").toString();
+
+        respObject.remove("sign");    // 删除sign节点
+        respObject.put("open_key", com.happy.Unitil_nsh.TestParams.OPEN_KEY);
+        System.out.println("==========开始验签==========");
+        String veriSign = sign(JSONObject.toJavaObject(respObject, Map.class));    // 按A~z排序,串联成字符串,先进行sha1加密(小写),再进行md5加密(小写),得到签名
+
+        if (respSign.equals(veriSign)) {
+            System.out.println("==========验签成功==========");
+
+            return true;
+        }
+
+        return false;
+    }
+
+    /**
+     * AES加密,再二进制转十六进制(bin2hex)
+     *
+     * @param postmap 说明:
+     * @throws Exception
+     */
+    public static void handleEncrypt(TreeMap<String, ?> datamap, TreeMap<String, String> postmap) throws Exception {
+
+        JSONObject dataobj = JSONObject.parseObject(JSON.toJSONString(datamap));
+        System.out.println(dataobj);
+        String data = com.happy.Unitil_nsh.TLinxAESCoder.encrypt(dataobj.toString(), com.happy.Unitil_nsh.TestParams.OPEN_KEY);    // AES加密,并bin2hex
+        System.out.println("====加密后的data= " + data);
+        postmap.put("data", data);
+    }
+
+    /**
+     * 签名
+     *
+     * @param postmap
+     */
+    public static void handleSign(TreeMap<String, String> postmap) {
+        Map<String, String> veriDataMap = new HashMap<String, String>();
+
+        veriDataMap.putAll(postmap);
+        veriDataMap.put("open_key", com.happy.Unitil_nsh.TestParams.OPEN_KEY);
+
+        // 签名
+        String sign = sign(veriDataMap);
+
+        System.out.println("====已签名字符串= " + sign);
+        postmap.put("sign", sign);
+    }
+
+    /**
+     * 签名(商户对账单下载接口)
+     *
+     * @param postmap
+     */
+    public static void handleSign(TreeMap<String, String> postmap, String pass) {
+        Map<String, String> veriDataMap = new HashMap<String, String>();
+
+        veriDataMap.putAll(postmap);
+        String sha1Str = com.happy.Unitil_nsh.TLinxSHA1.SHA1(pass);
+        String md5Str = com.happy.Unitil_nsh.TLinxMD5.MD5Encode(sha1Str).toLowerCase();
+        System.out.println("====sha1Str= " + sha1Str);
+        System.out.println("====md5Str= " + md5Str);
+        veriDataMap.put("pass", md5Str);
+
+        // 签名
+        String sign = sign(veriDataMap);
+
+        System.out.println("====已签名字符串= " + sign);
+        postmap.put("sign", sign);
+    }
+
+    /**
+     * 根据返回格式来选择post请求处理方式
+     *
+     * @param postmap
+     * @param interfaceName
+     * @param tarType
+     * @return
+     */
+    public static String handlePostbyTarType(TreeMap<String, String> postmap, String interfaceName, String tarType) {
+        if ("gzip".equals(tarType)) {
+            return handlePostGZIP(postmap, interfaceName);
+        } else {
+            return handlePost(postmap, interfaceName);
+        }
+    }
+
+    /**
+     * 请求接口
+     *
+     * @param postmap
+     * @return 响应字符串
+     */
+    public static String handlePost(TreeMap<String, String> postmap, String interfaceName) {
+        String url = com.happy.Unitil_nsh.TestParams.OPEN_URL + interfaceName;
+        System.out.println("====请求地址= " + url);
+        if (url.contains("https")) {
+            return HttpsUtil.httpMethodPost(url, postmap, "UTF-8");
+        } else {
+            return com.happy.Unitil_nsh.HttpUtil.httpMethodPost(url, postmap, "UTF-8");
+        }
+    }
+
+    public static String handlePostGZIP(TreeMap<String, String> postmap, String interfaceName) {
+        String url = com.happy.Unitil_nsh.TestParams.OPEN_URL + interfaceName;
+        if (url.contains("https")) {
+            return HttpsUtil.httpMethodPostGZIP(url, postmap, "UTF-8");
+        } else {
+            return com.happy.Unitil_nsh.HttpUtil.httpMethodPostGZIP(url, postmap, "UTF-8");
+        }
+    }
+
+    /**
+     * 十六进制字符串转byte数组
+     */
+    public static byte[] hex2byte(String strhex) {
+        if (strhex == null)
+            return null;
+
+        int l = strhex.length();
+        if (l % 2 == 1)
+            return null;
+
+        byte[] b = new byte[l / 2];
+        for (int i = 0; i != l / 2; ++i)
+            b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2), 16);
+
+        return b;
+    }
+
+    /**
+     * byte数组转十六进制字符串
+     */
+    public static String byte2hex(byte[] result) {
+        StringBuffer sb = new StringBuffer(result.length * 2);
+        for (int i = 0; i < result.length; i++) {
+            int hight = ((result[i] >> 4) & 0x0f);
+            int low = result[i] & 0x0f;
+            sb.append(hight > 9 ? (char) ((hight - 10) + 'a') : (char) (hight + '0'));
+            sb.append(low > 9 ? (char) ((low - 10) + 'a') : (char) (low + '0'));
+        }
+        return sb.toString();
+    }
+
+    /**
+     * 排序
+     *
+     * @param paramMap
+     * @return
+     * @throws Exception
+     */
+    public static String sort(Map paramMap) throws Exception {
+        String sort = "";
+        com.happy.Unitil_nsh.TLinxMapUtil signMap = new com.happy.Unitil_nsh.TLinxMapUtil();
+        if (paramMap != null) {
+            String key;
+            for (Iterator it = paramMap.keySet().iterator(); it.hasNext(); ) {
+                key = (String) it.next();
+                String value = ((paramMap.get(key) != null) && (!("".equals(paramMap.get(key).toString())))) ? paramMap.get(key).toString() : "";
+                signMap.put(key, value);
+            }
+            signMap.sort();
+            for (Iterator it = signMap.keySet().iterator(); it.hasNext(); ) {
+                key = (String) it.next();
+                sort = sort + key + "=" + signMap.get(key).toString() + "&";
+            }
+            if ((sort != null) && (!("".equals(sort)))) {
+                sort = sort.substring(0, sort.length() - 1);
+            }
+        }
+        return sort;
+    }
+
+    /**
+     * unicode转中文
+     *
+     * @param unicode
+     * @return
+     */
+    public static String unicodeToCn(String unicode) {
+        /** 以 \ u 分割,因为java注释也能识别unicode,因此中间加了一个空格*/
+        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
+        Matcher matcher = pattern.matcher(unicode);
+        char ch;
+        while (matcher.find()) {
+            ch = (char) Integer.parseInt(matcher.group(2), 16);
+            unicode = unicode.replace(matcher.group(1), ch + "");
+        }
+        return unicode;
+    }
+
+    /**
+     * Method main
+     * Description 说明:
+     *
+     * @param args 说明:
+     */
+    public static void main(String[] args) {
+
+    }
+}
+
+
+
+//~ Formatted by Jindent --- http://www.jindent.com

+ 49 - 0
TLinxAESCoder.java

@@ -0,0 +1,49 @@
+/**
+ * @Filename: TLinxAESCoder.java
+ * @Author锛歝aiqf
+ * @Date锛�016-4-12
+ */
+package com.happy.Unitil_nsh;
+
+import javax.crypto.Cipher;
+import javax.crypto.spec.SecretKeySpec;
+
+/**
+ * @Class: TLinxAESCoder.java
+ * @Description: AES加解密类
+ * @Author:caiqf
+ * @Date:2016-4-12
+ */
+public class TLinxAESCoder {
+    private static String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
+    private static String KEY_ALGORITHM = "AES";
+
+    public static String decrypt(String sSrc, String sKey) throws Exception {
+        SecretKeySpec skeySpec = new SecretKeySpec(sKey.getBytes("ASCII"), KEY_ALGORITHM);
+        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
+        cipher.init(2, skeySpec);
+        byte[] encrypted1 = TLinx2Util.hex2byte(sSrc);
+        byte[] original = cipher.doFinal(encrypted1);
+        return new String(original, "UTF-8");
+    }
+
+    public static String encrypt(String sSrc, String sKey) throws Exception {
+        System.out.println("====data加密前的明文= " + sSrc);
+        SecretKeySpec skeySpec = new SecretKeySpec(sKey.getBytes("ASCII"), KEY_ALGORITHM);
+        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
+        cipher.init(1, skeySpec);
+        byte[] encrypted = cipher.doFinal(sSrc.getBytes("UTF-8"));
+        return TLinx2Util.byte2hex(encrypted);
+    }
+
+    public static void main(String[] args) {
+        String data = "";
+        String str = null;
+        try {
+            str = decrypt(data, "");
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        System.out.println(str);
+    }
+}

+ 43 - 0
TLinxMD5.java

@@ -0,0 +1,43 @@
+package com.happy.Unitil_nsh;
+
+//~--- JDK imports ------------------------------------------------------------
+
+import java.security.MessageDigest;
+
+//~--- classes ----------------------------------------------------------------
+
+/**
+ * Class TLinxMD5
+ * Description
+ * Create 2016-02-25 01:03:21
+ *
+ * @author Benny.YEE
+ */
+public class TLinxMD5 {
+
+    /**
+     * Method MD5Encode
+     * Description 说明:
+     *
+     * @param origin 说明:
+     * @return 返回值说明:
+     */
+    public static String MD5Encode(String origin) {
+        String resultString = null;
+
+        try {
+            resultString = origin;
+
+            MessageDigest md = MessageDigest.getInstance("MD5");
+
+            resultString = TLinx2Util.byte2hex(md.digest(resultString.getBytes("utf-8")));
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return resultString;
+    }
+
+}
+
+
+//~ Formatted by Jindent --- http://www.jindent.com

+ 46 - 0
TLinxMapUtil.java

@@ -0,0 +1,46 @@
+/**
+ * @Filename: TLinxMapUtil.java
+ * @Author:caiqf
+ * @Date�?014-10-11
+ */
+package com.happy.Unitil_nsh;
+
+import java.util.*;
+
+/**
+ * @Class: TLinxMapUtil.java
+ * @Description:
+ * @Author:caiqf
+ * @Date�?014-10-11
+ */
+@SuppressWarnings("all")
+public class TLinxMapUtil {
+    private Map map = new HashMap();
+    private Set keySet = map.keySet();
+
+    public Object get(String key) {
+        return map.get(key);
+    }
+
+    public void put(String key, Object value) {
+        map.put(key, value);
+    }
+
+    public void sort() {
+        List list = new ArrayList(map.keySet());
+
+//		Collections.sort(list, new Comparator() {
+//			public int compare(Object a, Object b) {
+//				return a.toString().compareTo(b.toString());
+//			}
+//		});
+
+        this.keySet = new TreeSet(list);
+    }
+
+    public Set keySet() {
+        return this.keySet;
+    }
+
+
+}

+ 34 - 0
TLinxSHA1.java

@@ -0,0 +1,34 @@
+/**
+ * @Filename: TLinxSHA1.java
+ * @Author?caiqf
+ * @Date??016-4-12
+ */
+package com.happy.Unitil_nsh;
+
+import java.security.MessageDigest;
+
+/**
+ * @Class: TLinxSHA1.java
+ * @Description: SHA-1??????
+ */
+public class TLinxSHA1 {
+    public static String SHA1(String decript) {
+        try {
+            MessageDigest digest = MessageDigest.getInstance("SHA-1");
+            digest.update(decript.getBytes("UTF-8"));
+            byte[] messageDigest = digest.digest();
+            StringBuilder hexString = new StringBuilder();
+            for (byte message : messageDigest) {
+                String shaHex = Integer.toHexString(message & 0xFF);
+                if (shaHex.length() < 2)
+                    hexString.append(0);
+
+                hexString.append(shaHex);
+            }
+            return hexString.toString();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return "";
+    }
+}

+ 57 - 0
Test.java

@@ -0,0 +1,57 @@
+package testExport;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Locale;
+
+
+public class Test {
+
+    //记住不要导错包  代码亲测可用
+    public static void main(String[] args) {
+        String webUrl2 = "http://www.baidu.com";//百度
+        String webUrl3 = "http://www.taobao.com";//淘宝
+        String webUrl4 = "http://www.ntsc.ac.cn";//中国科学院国家授时中心
+        String webUrl5 = "http://www.360.cn";//360
+        System.out.println(getWebsiteDatetime(webUrl2) + " [百度]");
+        System.out.println(getWebsiteDatetime(webUrl3) + " [淘宝]");
+        System.out.println(getWebsiteDatetime(webUrl4) + " [中国科学院国家授时中心]");
+        System.out.println(getWebsiteDatetime(webUrl5) + " [360安全卫士]");
+        Calendar cal = Calendar.getInstance();
+        // 往前多少天的访客
+        cal.add(Calendar.DATE,   -1);
+        String startTime = new SimpleDateFormat( "yyyyMMdd").format(cal.getTime());
+        System.out.println(startTime);
+    }
+
+    /**
+     * 获取指定网站的日期时间
+     *
+     * @param webUrl
+     * @return
+     */
+    public static String getWebsiteDatetime(String webUrl){
+        try {
+            URL url = new URL(webUrl);// 取得资源对象
+            URLConnection uc = url.openConnection();// 生成连接对象
+            uc.connect();// 发出连接
+            long ld = uc.getDate();// 读取网站日期时间
+            Date date = new Date(ld);// 转换为标准时间对象
+            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);// 输出北京时间
+            return sdf.format(date);
+        } catch (MalformedURLException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+}
+
+

+ 37 - 0
TestParams.java

@@ -0,0 +1,37 @@
+package com.happy.Unitil_nsh;
+
+/**
+ * Interface TestParams
+ * Description	说明:
+ * Create 2017-04-19 14:26:00
+ *
+ * @author Benny.YEE
+ */
+public interface TestParams {
+
+    //    测试环境
+//    String OPEN_ID = "5fb33938bb819024b8ed719edf221840";
+    String OPEN_ID = "74969401869b175660817b4369e5a911";
+    String OPEN_KEY = "ba5c30ce48fbfb4464a5a855a960c802";
+    //    测试环境地址
+    String OPEN_URL = "https://api.jxnxs.com/mct1/";
+
+    //    接口名称
+    String PAYLIST = "paylist";
+    String ORDERLIST = "order";
+    String ORDERVIEW = "order/view";
+    String PAYORDER = "payorder";
+    String QUERYPAYSTATUS = "paystatus";
+    String PAYCANCEL = "paycancel";
+    String PAYREFUND = "payrefund";
+    String BILL = "bill";
+    String PREORDER = "preorder";
+
+    // {"open_id":"5494ec3310685daa218382619dd20e27","open_key":"611764d05a545bb7bb08cbd457f7dac1"}
+
+    // https://q.jxnxs.com
+    // https://q.jxnxs.com/newpay?O=5494ec3310685daa218382619dd20e27&out_no=798465321465&amount=1
+}
+
+
+//~ Formatted by Jindent --- http://www.jindent.com

+ 130 - 0
TimeExchange.java

@@ -0,0 +1,130 @@
+package com.happy.Until;
+
+import java.sql.Timestamp;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+/**
+ * 时间转化工具 date转为时间戳 时间戳转date 互相与String的转换
+ * 所有出现的String time 格式都必须为(yyyy-MM-dd HH:mm:ss),否则出错
+ * @author 赵仁杰
+ *
+ */
+public class TimeExchange {
+
+    /**
+     * String(yyyy-MM-dd HH:mm:ss) 转 Date
+     *
+     * @param time
+     * @return
+     * @throws ParseException
+     */
+    // String date = "2010/05/04 12:34:23";
+    public static Date StringToDate(String time) throws ParseException {
+
+        Date date = new Date();
+        // 注意format的格式要与日期String的格式相匹配
+        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        try {
+            date = dateFormat.parse(time);
+            System.out.println(date.toString());
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+        return date;
+    }
+
+    /**
+     * Date转为String(yyyy-MM-dd HH:mm:ss)
+     *
+     * @param time
+     * @return
+     */
+    public static String DateToString(Date time) {
+        String dateStr = "";
+        Date date = new Date();
+        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH/mm/ss");
+        try {
+            dateStr = dateFormat.format(time);
+            System.out.println(dateStr);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return dateStr;
+    }
+    /**
+     * String(yyyy-MM-dd HH:mm:ss)转10位时间戳
+     * @param time
+     * @return
+     */
+    public static Integer StringToTimestamp(String time){
+
+        int times = 0;
+        try {
+            times = (int) ((Timestamp.valueOf(time).getTime())/1000);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        if(times==0){
+            System.out.println("String转10位时间戳失败");
+        }
+        return times;
+
+    }
+    /**
+     * 10位int型的时间戳转换为String(yyyy-MM-dd HH:mm:ss)
+     * @param time
+     * @return
+     */
+    public static String timestampToString(Integer time){
+        //int转long时,先进行转型再进行计算,否则会是计算结束后在转型
+        long temp = (long)time*1000;
+        Timestamp ts = new Timestamp(temp);
+        String tsStr = "";
+        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        try {
+            //方法一
+            tsStr = dateFormat.format(ts);
+            System.out.println(tsStr);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return tsStr;
+    }
+    /**
+     * 10位时间戳转Date
+     * @param time
+     * @return
+     */
+    public static Date TimestampToDate(Integer time){
+        long temp = (long)time*1000;
+        Timestamp ts = new Timestamp(temp);
+        Date date = new Date();
+        try {
+            date = ts;
+            //System.out.println(date);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return date;
+    }
+    /**
+     * Date类型转换为10位时间戳
+     * @param time
+     * @return
+     */
+    public static Integer DateToTimestamp(Date time){
+        Timestamp ts = new Timestamp(time.getTime());
+
+        return (int) ((ts.getTime())/1000);
+    }
+    public static void main(String [] args){
+        System.out.println(StringToTimestamp("2011-05-09 11:49:45"));
+        System.out.println(DateToTimestamp(TimestampToDate(StringToTimestamp("2011-05-09 11:49:45"))));
+    }
+
+}
+

+ 21 - 0
TokenUtil.java

@@ -0,0 +1,21 @@
+package com.happy.Until;
+
+import org.apache.commons.lang.StringUtils;
+
+import javax.servlet.http.HttpServletRequest;
+
+public class TokenUtil {
+    /**
+     * 获取请求的token
+     */
+    public static String getRequestToken(HttpServletRequest httpRequest) {
+
+        //从header中获取token
+        String token = httpRequest.getHeader("token");
+        //如果header中不存在token,则从参数中获取token
+        if (StringUtils.isBlank(token)) {
+            token = httpRequest.getParameter("token");
+        }
+        return token;
+    }
+}

+ 84 - 0
TongYiReturn.java

@@ -0,0 +1,84 @@
+package com.happy.Until.weixin;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+/**
+ * 调用统一下单接口返回的数据实体类
+ * @author QT-666
+ *
+ */
+@XmlRootElement(name="xml")
+public class TongYiReturn {
+    private String return_code; //
+    private String return_msg;  // 
+    private String appid;       // 调用接口提交的公众账号ID
+    private String mch_id;      // 调用接口提交的商户号
+    private String nonce_str;   //微信返回的随机字符串
+    private String sign;        //微信返回的签名值,详见签名算法
+    private String prepay_id;   //微信生成的预支付会话标识,用于后续接口调用中使用,该值有效期为2小时
+    private String result_code; //SUCCESS/FAIL
+    private String trade_type;  //交易类型,取值为:JSAPI,NATIVE,APP等,说明详见参数规定
+	public String getReturn_code() {
+		return return_code;
+	}
+	public void setReturn_code(String return_code) {
+		this.return_code = return_code;
+	}
+	public String getReturn_msg() {
+		return return_msg;
+	}
+	public void setReturn_msg(String return_msg) {
+		this.return_msg = return_msg;
+	}
+	public String getAppid() {
+		return appid;
+	}
+	public void setAppid(String appid) {
+		this.appid = appid;
+	}
+	public String getMch_id() {
+		return mch_id;
+	}
+	public void setMch_id(String mch_id) {
+		this.mch_id = mch_id;
+	}
+	public String getNonce_str() {
+		return nonce_str;
+	}
+	public void setNonce_str(String nonce_str) {
+		this.nonce_str = nonce_str;
+	}
+	public String getSign() {
+		return sign;
+	}
+	public void setSign(String sign) {
+		this.sign = sign;
+	}
+	public String getPrepay_id() {
+		return prepay_id;
+	}
+	public void setPrepay_id(String prepay_id) {
+		this.prepay_id = prepay_id;
+	}
+	public String getResult_code() {
+		return result_code;
+	}
+	public void setResult_code(String result_code) {
+		this.result_code = result_code;
+	}
+	public String getTrade_type() {
+		return trade_type;
+	}
+	public void setTrade_type(String trade_type) {
+		this.trade_type = trade_type;
+	}
+	@Override
+	public String toString() {
+		return "TongYiReturn [return_code=" + return_code + ", return_msg="
+				+ return_msg + ", appid=" + appid + ", mch_id=" + mch_id
+				+ ", nonce_str=" + nonce_str + ", sign=" + sign
+				+ ", prepay_id=" + prepay_id + ", result_code=" + result_code
+				+ ", trade_type=" + trade_type + "]";
+	}
+    
+}

+ 137 - 0
Upload.java

@@ -0,0 +1,137 @@
+package com.happy.action;
+
+import com.happy.Until.ResponseUtil;
+import jxl.Sheet;
+import jxl.Workbook;
+import net.sf.json.JSONObject;
+import org.apache.commons.fileupload.FileItem;
+import org.apache.commons.fileupload.FileUploadException;
+import org.apache.commons.fileupload.disk.DiskFileItemFactory;
+import org.apache.commons.fileupload.servlet.ServletFileUpload;
+import org.apache.struts2.ServletActionContext;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.support.ClassPathXmlApplicationContext;
+
+import javax.servlet.ServletException;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.sql.DataSource;
+import java.io.File;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+
+@WebServlet("/upload")
+public class Upload extends HttpServlet {
+
+    private static final long serialVersionUID = 1L;
+
+    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+        request.setCharacterEncoding("utf-8");
+        response.setContentType("text/html;charset=utf-8");
+        /*
+        InputStream in = request.getInputStream();
+        BufferedReader br = new BufferedReader(new InputStreamReader(in));
+        String str = "";
+        while((str=br.readLine())!=null){
+            System.out.println(str);
+        }
+        */
+        System.out.println("[-------------------------------------------------------]");
+        String filepath=request.getServletContext().getRealPath("/download/");
+        File file = new File(filepath);
+        if(!file.exists()) {
+            file.mkdir();
+        }
+        DiskFileItemFactory factory = new DiskFileItemFactory();
+        ServletFileUpload upload = new ServletFileUpload(factory);
+        try {
+            List<FileItem> items= upload.parseRequest(request);
+            String ex = "";
+            for(FileItem item: items) {
+                ex = filepath+item.getName();
+                if(!item.isFormField()) {
+                    item.write(new File(filepath+item.getName()));
+                }
+                if(item.isFormField()){
+                    System.out.println(item.getString());
+                    System.out.println(item.getFieldName());
+                }
+            }
+            File files = new File(ex);
+            Workbook workbook = Workbook.getWorkbook(files);
+            Sheet sheet = workbook.getSheet(0);
+            ArrayList<ArrayList> aa = new ArrayList<>();
+            for (int i=1; i<sheet.getRows(); i++){
+                ArrayList a = new ArrayList();
+                for (int j=0; j<sheet.getColumns(); j++){
+                    a.add(sheet.getCell(j, i).getContents());
+                }
+                aa.add(a);
+            }
+            ApplicationContext ac = new ClassPathXmlApplicationContext(
+                    "applicationContext.xml");
+            DataSource dataSource = (DataSource) ac.getBean("slaveDataSource");
+            Connection conn = null;
+            ResultSet rs = null;
+            try {
+                conn = dataSource.getConnection();
+                PreparedStatement ps = conn.prepareStatement("select * from build_water order by id asc");
+                rs = ps.executeQuery();
+                System.out.println("成功获取数据");
+                ArrayList a1 = new ArrayList();
+                while (rs.next()){
+                    a1.add(rs.getInt("id"));
+                }
+                for (int i=0; i<aa.size(); i++){
+                    if(!a1.contains(Integer.parseInt(String.valueOf(aa.get(i).get(0))))) {
+                        String sql = String.format("insert into build_water(id, school, build, floors, dom, user_id) " +
+                                "values('%s', '%s', '%s', '%s', '%s', '%s')", aa.get(i).get(0), aa.get(i).get(1), aa.get(i).get(2), aa.get(i).get(3), aa.get(i).get(4), aa.get(i).get(5));
+                        PreparedStatement pst = conn.prepareStatement(sql);
+                        pst.execute();
+                        pst.close();
+                    }else{
+                        String sql = String.format("update build_water set school='%s', build='%s', floors='%s', dom='%s', user_id='%s' " +
+                                "where id='%s'", aa.get(i).get(1), aa.get(i).get(2), aa.get(i).get(3), aa.get(i).get(4), aa.get(i).get(5), aa.get(i).get(0));
+                        PreparedStatement pst2 = conn.prepareStatement(sql);
+                        pst2.execute();
+                        pst2.close();
+                    }
+                }
+            } catch (SQLException e) {
+                System.out.println("导入失败!");
+                response.setContentType("text/html;charset=utf-8");
+                PrintWriter out = response.getWriter();
+                out.println("有重复id");
+                out.flush();
+                out.close();
+            } finally {
+                try {
+                    if (conn != null) {
+                        conn.close();
+                    }
+                } catch (SQLException e) {
+                    // TODO: handle exception
+                }
+            }
+        } catch (FileUploadException e) {
+            e.printStackTrace();
+        } catch (Exception e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+        System.out.println("导入成功!");
+        response.setContentType("text/html;charset=utf-8");
+        PrintWriter out = response.getWriter();
+        out.println("导入成功");
+        out.flush();
+        out.close();
+    }
+}

+ 163 - 0
User.java

@@ -0,0 +1,163 @@
+package com.happy.action;
+
+import com.happy.Model.Login;
+import com.happy.Model.Users;
+import com.happy.Until.ResUtil;
+import com.happy.service.UserService;
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+import com.opensymphony.xwork2.ActionSupport;
+import net.sf.json.JSONObject;
+import org.apache.struts2.ServletActionContext;
+import org.apache.struts2.interceptor.ServletRequestAware;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.util.HashMap;
+import java.util.List;
+
+public class User extends ActionSupport implements ServletRequestAware {
+
+    private HttpServletRequest request;
+
+    public HttpServletResponse response;
+
+    @Resource
+    private UserService userService;
+
+    public String card_number;
+
+    public String password;
+
+    public String user;
+
+    public HttpServletRequest getRequest() {
+        return request;
+    }
+
+    public void setRequest(HttpServletRequest request) {
+        this.request = request;
+    }
+
+    public void setServletRequest(HttpServletRequest request) {
+        this.request = request;
+    }
+
+    public HttpServletResponse getResponse() {
+        return response;
+    }
+
+    public void setResponse(HttpServletResponse response) {
+        this.response = response;
+    }
+
+    public String getCard_number() {
+        return card_number;
+    }
+
+    public void setCard_number(String card_number) {
+        this.card_number = card_number;
+    }
+
+    public String getPassword() {
+        return password;
+    }
+
+    public void setPassword(String password) {
+        this.password = password;
+    }
+
+    public UserService getUserService() {
+        return userService;
+    }
+
+    public void setUserService(UserService userService) {
+        this.userService = userService;
+    }
+
+    public String getUser() {
+        return user;
+    }
+
+    public void setUser(String user) {
+        this.user = user;
+    }
+
+    public String log() throws Exception {
+        JSONObject resultJson = new JSONObject();
+        List<Login> login = userService.log(card_number, password);
+        if (login == null) {
+            resultJson.put("info", "信息错误!");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+        } else {
+            String access_token = userService.createToken(login.get(0));
+            resultJson.put("access_token", access_token);
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+        }
+        return null;
+    }
+
+    public String list(){
+        return "list";
+    }
+
+
+//    public String stu_info() throws Exception {
+//        JSONObject resultJson = new JSONObject();
+//        if(user != null) {
+//            Gson gson=new Gson();
+//            HashMap<String, Object> userMap = gson.fromJson(user.toString(), new TypeToken<HashMap<String, Object>>(){}.getType());
+//            String nb = userMap.get("card_number").toString();
+//            List<Users> use = userService.selectByStu(nb);
+//            if(use == null) {
+//                Users users = new Users();
+//                System.out.println(userMap);
+//                users.setCard_number(userMap.get("card_number").toString());
+//                users.setUser_name(userMap.get("name").toString());
+//                users.setUser_phone(userMap.get("telephone").toString());
+//                users.setCampus(userMap.get("campus").toString());
+//                users.setBuild(userMap.get("dorm_number").toString());
+//                users.setDom(userMap.get("dorm_number").toString());
+//                users.setId_card(userMap.get("id_card").toString());
+//                userService.insertUser(users);
+//                resultJson.put("mess", "绑定成功!");
+//                resultJson.put("info", users);
+//                ResUtil.write(resultJson, ServletActionContext.getResponse());
+//            }else {
+//                resultJson.put("erro", "请不要重复绑定!");
+//                ResUtil.write(resultJson, ServletActionContext.getResponse());
+//            }
+//        }else{
+//            resultJson.put("erro", "未获取到数据!");
+//            ResUtil.write(resultJson, ServletActionContext.getResponse());
+//        }
+//        return null;
+//    }
+//
+//    public String get_stu() throws Exception {
+//        JSONObject resultJson = new JSONObject();
+//        List<Users> use = userService.selectByCard(card_number);
+//        if (use == null){
+//            resultJson.put("info", "未查询到绑定信息");
+//        }else {
+//            resultJson.put("info", use);
+//        }
+//        ResUtil.write(resultJson, ServletActionContext.getResponse());
+//        return null;
+//    }
+//
+//    public String del_stu() throws Exception {
+//        JSONObject resultJson = new JSONObject();
+//        int num = userService.delUser(card_number);
+//        if (num > 0) {
+//            resultJson.put("mess", "删除成功");
+//        }else {
+//            resultJson.put("mess", "删除异常");
+//        }
+//        ResUtil.write(resultJson, ServletActionContext.getResponse());
+//        return null;
+//    }
+}

+ 30 - 0
UserDao.java

@@ -0,0 +1,30 @@
+package com.happy.dao;
+
+import com.happy.Model.Login;
+import com.happy.Model.Users;
+
+import java.util.List;
+
+public interface UserDao {
+
+	public List<Login> log(String card_number, String password);
+
+	public int save(Login login);
+
+	public List<Login> findByToken(String access_token);
+
+	public List<Users> selectByStu(String stu_number);
+
+	public List<Users> selectByCard_number(String card_number);
+
+	public int insertUser(Users users);
+
+	public int delUser(String card_number);
+
+	public int updateOpenid(String openid,String stu_number, String card_number);
+
+	public List<Users> queryByopenid(String openid);
+
+	public int updateDom(String campus, String build, String dom, String stu_number);
+
+}

+ 170 - 0
UserDaoImpl.java

@@ -0,0 +1,170 @@
+package com.happy.dao.impl;
+
+import com.happy.Model.Login;
+import com.happy.Model.Users;
+import com.happy.dao.UserDao;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.jdbc.core.BeanPropertyRowMapper;
+import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
+import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
+import org.springframework.stereotype.Repository;
+
+import java.util.List;
+
+@Repository("userDao")
+public class UserDaoImpl implements UserDao {
+
+	@Autowired
+	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
+
+	public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
+		return namedParameterJdbcTemplate;
+	}
+
+	public void setNamedParameterJdbcTemplate(
+			NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
+		this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
+	}
+
+	public List<Login> log(String card_number, String password){
+		String sql="select * from login where card_number=:card_number and password=:password";
+		MapSqlParameterSource sps = new MapSqlParameterSource();
+		sps.addValue("card_number", card_number);
+		sps.addValue("password", password);
+		List<Login> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Login>(Login.class));
+		if(list != null && list.size() >0){
+			return list;
+		}
+		return null;
+	}
+
+	public int save(Login login){
+        String sql = "update login set login_time=:login_time, expire_time=:expire_time, access_token=:access_token where card_number=:card_number";
+		MapSqlParameterSource sps = new MapSqlParameterSource();
+		sps.addValue("login_time", login.getLogin_time());
+		sps.addValue("expire_time", login.getExpire_time());
+		sps.addValue("access_token", login.getAccess_token());
+		sps.addValue("card_number", login.getCard_number());
+		int num = 0;
+		try{
+			num = namedParameterJdbcTemplate.update(sql, sps);
+		}
+		catch(Exception e){
+			e.printStackTrace();
+		}
+		return num;
+	}
+
+	public List<Login> findByToken(String access_token){
+		String sql = "select * from login where access_token=:access_token";
+		MapSqlParameterSource sps = new MapSqlParameterSource();
+		sps.addValue("access_token", access_token);
+		List<Login> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Login>(Login.class));
+		if(list != null && list.size() >0){
+			return list;
+		}
+		return null;
+	}
+
+	public List<Users> selectByStu(String stu_number){
+		String sql = "select * from users where stu_number=:stu_number";
+		MapSqlParameterSource sps = new MapSqlParameterSource();
+		sps.addValue("stu_number", stu_number);
+		List<Users> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Users>(Users.class));
+		if (list != null && list.size() > 0) {
+			return list;
+		}
+		return null;
+	}
+
+	public List<Users> selectByCard_number(String card_number){
+		String sql = "select * from users where card_number=:card_number";
+		MapSqlParameterSource sps = new MapSqlParameterSource();
+		sps.addValue("card_number", card_number);
+		List<Users> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Users>(Users.class));
+		if (list != null && list.size() > 0) {
+			return list;
+		}
+		return null;
+	}
+
+    public int insertUser(Users users){
+		String sql = "insert into users(card_number, stu_number, user_name, user_phone, campus, build, dom, id_card, openid) values(:card_number, :stu_number,:user_name, :user_phone, :campus, :build, :dom, :id_card, :openid)";
+		MapSqlParameterSource sps = new MapSqlParameterSource();
+		sps.addValue("card_number", users.getCard_number());
+		sps.addValue("stu_number", users.getStu_number());
+		sps.addValue("user_name", users.getUser_name());
+		sps.addValue("user_phone", users.getUser_phone());
+		sps.addValue("campus", users.getCampus());
+		sps.addValue("build", users.getBuild());
+		sps.addValue("dom", users.getDom());
+		sps.addValue("id_card", users.getId_card());
+		sps.addValue("openid", users.getOpenid());
+		int num = 0;
+		try{
+			num = namedParameterJdbcTemplate.update(sql, sps);
+		}
+		catch(Exception e){
+			e.printStackTrace();
+		}
+		return num;
+	}
+
+	public int delUser(String card_number){
+		String sql = "delete from users where card_number=:card_number";
+		MapSqlParameterSource sps = new MapSqlParameterSource();
+		sps.addValue("card_number", card_number);
+		int num = 0;
+		try{
+			num = namedParameterJdbcTemplate.update(sql, sps);
+		}
+		catch(Exception e){
+			e.printStackTrace();
+		}
+		return num;
+	}
+
+	public int updateOpenid(String openid,String stu_number, String card_number){
+		String sql = "update users set openid=:openid where stu_number=:stu_number and card_number=:card_number";
+		MapSqlParameterSource sps = new MapSqlParameterSource();
+		sps.addValue("openid", openid);
+		sps.addValue("stu_number", stu_number);
+		sps.addValue("card_number", card_number);
+		int num = 0;
+		try{
+			num = namedParameterJdbcTemplate.update(sql, sps);
+		}
+		catch(Exception e){
+			e.printStackTrace();
+		}
+		return num;
+	}
+
+	public List<Users> queryByopenid(String openid){
+		String sql = "select * from users where openid=:openid";
+		MapSqlParameterSource sps = new MapSqlParameterSource();
+		sps.addValue("openid", openid);
+		List<Users> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Users>(Users.class));
+		if (list != null && list.size() > 0) {
+			return list;
+		}
+		return null;
+	}
+
+	public int updateDom(String campus, String build, String dom, String stu_number){
+		String sql = "update users set campus=:campus, build=:build, dom=:dom where stu_number=:stu_number";
+		MapSqlParameterSource sps = new MapSqlParameterSource();
+		sps.addValue("campus", campus);
+		sps.addValue("build", build);
+		sps.addValue("dom", dom);
+		sps.addValue("stu_number", stu_number);
+		int num = 0;
+		try{
+			num = namedParameterJdbcTemplate.update(sql, sps);
+		}
+		catch(Exception e){
+			e.printStackTrace();
+		}
+		return num;
+	}
+}

+ 12 - 0
UserLoginToken.java

@@ -0,0 +1,12 @@
+package com.happy.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target({ElementType.METHOD, ElementType.TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+public @interface UserLoginToken {
+    boolean required() default true;
+}

+ 31 - 0
UserService.java

@@ -0,0 +1,31 @@
+package com.happy.service;
+
+import com.happy.Model.Login;
+import com.happy.Model.Users;
+
+import java.util.List;
+
+public interface UserService {
+
+	public List<Login> log(String card_number, String password);
+
+	public int save(Login login);
+
+	public String createToken(Login login);
+
+	public List<Login> findByToken(String access_token);
+
+	public List<Users> selectByStu(String stu_number);
+
+	public List<Users> selectByCard_number(String card_number);
+
+	public int insertUser(Users users);
+
+	public int delUser(String card_number);
+
+	public int updateOpenid(String openid,String stu_number, String card_number);
+
+	public List<Users> queryByopenid(String openid);
+
+	public int updateDom(String campus, String build, String dom, String stu_number);
+}

+ 84 - 0
UserServiceImpl.java

@@ -0,0 +1,84 @@
+package com.happy.service.impl;
+
+import com.happy.Model.Login;
+import com.happy.Model.Users;
+import com.happy.dao.UserDao;
+import com.happy.service.UserService;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.UUID;
+
+@Service("userService")
+public class UserServiceImpl implements UserService {
+	@Resource
+	private UserDao userDao;
+
+	public UserDao getUserDao() {
+		return userDao;
+	}
+
+	public void setUserDao(UserDao userDao) {
+		this.userDao = userDao;
+	}
+
+	public List<Login> log(String card_number, String password){
+		return userDao.log(card_number, password);
+	}
+
+	public int save(Login login){
+		return userDao.save(login);
+	}
+
+	//12小时后失效
+	private final static int EXPIRE = 12;
+
+	public String createToken(Login login) {
+		//用UUID生成token
+		String token = UUID.randomUUID().toString();
+		//当前时间
+		LocalDateTime now = LocalDateTime.now();
+		//过期时间
+		LocalDateTime expireTime = now.plusHours(EXPIRE);
+		//保存到数据库
+		login.setLogin_time(now.toString().replace("T", " "));
+		login.setExpire_time(expireTime.toString().replace("T", " "));
+		login.setAccess_token(token);
+		userDao.save(login);
+		return token;
+	}
+
+	public List<Login> findByToken(String access_token){
+		return userDao.findByToken(access_token);
+	}
+
+	public List<Users> selectByStu(String stu_number){
+		return userDao.selectByStu(stu_number);
+	}
+
+	public List<Users> selectByCard_number(String card_number){
+		return userDao.selectByCard_number(card_number);
+	}
+
+	public int insertUser(Users users){
+		return userDao.insertUser(users);
+	}
+
+	public int delUser(String card_number){
+		return userDao.delUser(card_number);
+	}
+
+	public int updateOpenid(String openid,String stu_number,String card_number){
+		return userDao.updateOpenid(openid, stu_number, card_number);
+	}
+
+	public List<Users> queryByopenid(String openid){
+		return userDao.queryByopenid(openid);
+	}
+
+	public int updateDom(String campus, String build, String dom, String stu_number){
+		return userDao.updateDom(campus, build, dom, stu_number);
+	}
+}

+ 124 - 0
Users.java

@@ -0,0 +1,124 @@
+package com.happy.Model;
+
+import java.math.BigDecimal;
+
+public class Users {
+
+     public Integer id;
+     public String stu_number;
+     public String card_number;
+     public String user_name;
+     public String user_phone;
+     public String user_level;
+     public double balance;
+     public String campus;
+     public String build;
+     public String dom;
+     public String id_card;
+     public String remark;
+     public String openid;
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public String getStu_number() {
+        return stu_number;
+    }
+
+    public void setStu_number(String stu_number) {
+        this.stu_number = stu_number;
+    }
+
+    public String getCard_number() {
+        return card_number;
+    }
+
+    public void setCard_number(String card_number) {
+        this.card_number = card_number;
+    }
+
+    public String getUser_name() {
+        return user_name;
+    }
+
+    public void setUser_name(String user_name) {
+        this.user_name = user_name;
+    }
+
+    public String getUser_phone() {
+        return user_phone;
+    }
+
+    public void setUser_phone(String user_phone) {
+        this.user_phone = user_phone;
+    }
+
+    public String getUser_level() {
+        return user_level;
+    }
+
+    public void setUser_level(String user_level) {
+        this.user_level = user_level;
+    }
+
+    public double getBalance() {
+        return balance;
+    }
+
+    public void setBalance(double balance) {
+        this.balance = balance;
+    }
+
+    public String getCampus() {
+        return campus;
+    }
+
+    public void setCampus(String campus) {
+        this.campus = campus;
+    }
+
+    public String getBuild() {
+        return build;
+    }
+
+    public void setBuild(String build) {
+        this.build = build;
+    }
+
+    public String getDom() {
+        return dom;
+    }
+
+    public void setDom(String dom) {
+        this.dom = dom;
+    }
+
+    public String getId_card() {
+        return id_card;
+    }
+
+    public void setId_card(String id_card) {
+        this.id_card = id_card;
+    }
+
+    public String getRemark() {
+        return remark;
+    }
+
+    public void setRemark(String remark) {
+        this.remark = remark;
+    }
+
+    public String getOpenid() {
+        return openid;
+    }
+
+    public void setOpenid(String openid) {
+        this.openid = openid;
+    }
+}

+ 0 - 0
Water.java


Some files were not shown because too many files changed in this diff