diff --git a/src/api/dzfcd/controller/LeaveController.java b/src/api/dzfcd/controller/LeaveController.java deleted file mode 100644 index c101243..0000000 --- a/src/api/dzfcd/controller/LeaveController.java +++ /dev/null @@ -1,7 +0,0 @@ -package api.dzfcd.controller; - -import javax.ws.rs.Path; - -@Path("/dzfcddev/leave") -public class LeaveController extends engine.dzfcd.controller.LeaveController { -} diff --git a/src/com/api/dzfcd/controller/LeaveController.java b/src/com/api/dzfcd/controller/LeaveController.java new file mode 100644 index 0000000..231fef3 --- /dev/null +++ b/src/com/api/dzfcd/controller/LeaveController.java @@ -0,0 +1,7 @@ +package com.api.dzfcd.controller; + +import javax.ws.rs.Path; + +@Path("/dzfcddev/leave") +public class LeaveController extends com.engine.dzfcd.controller.LeaveController { +} diff --git a/src/engine/dzfcd/controller/LeaveController.java b/src/com/engine/dzfcd/controller/LeaveController.java similarity index 51% rename from src/engine/dzfcd/controller/LeaveController.java rename to src/com/engine/dzfcd/controller/LeaveController.java index 4379e1d..1a6666e 100644 --- a/src/engine/dzfcd/controller/LeaveController.java +++ b/src/com/engine/dzfcd/controller/LeaveController.java @@ -1,7 +1,10 @@ -package engine.dzfcd.controller; +package com.engine.dzfcd.controller; import com.engine.common.util.ParamUtil; +import com.engine.common.util.ServiceUtil; import com.google.gson.Gson; +import com.engine.dzfcd.service.LeaveService; +import com.engine.dzfcd.service.impl.LeaveServiceImpl; import weaver.hrm.HrmUserVarify; import weaver.hrm.User; @@ -16,14 +19,18 @@ import java.util.Map; public class LeaveController { + public LeaveService getLeaveService(User user){ + return ServiceUtil.getService(LeaveServiceImpl.class, user); + } + @Path("/checkLeaveInt") @GET @Produces(MediaType.APPLICATION_JSON) public String checkLeaveInt(@Context HttpServletRequest request, @Context HttpServletResponse response) { -// User user = HrmUserVarify.getUser(request, response); -// Map params = ParamUtil.request2Map(request); -// Map resultDatas = getEntryService(user).checkBlackList(params); - return new Gson().toJson("resultDatas"); + User user = HrmUserVarify.getUser(request, response); + Map params = ParamUtil.request2Map(request); + Map resultDatas = getLeaveService(user).checkLeaveInt(params); + return new Gson().toJson(resultDatas); } } diff --git a/src/com/engine/dzfcd/service/LeaveService.java b/src/com/engine/dzfcd/service/LeaveService.java new file mode 100644 index 0000000..dc318b9 --- /dev/null +++ b/src/com/engine/dzfcd/service/LeaveService.java @@ -0,0 +1,7 @@ +package com.engine.dzfcd.service; + +import java.util.Map; + +public interface LeaveService { + Map checkLeaveInt(Map params); +} diff --git a/src/com/engine/dzfcd/service/impl/LeaveServiceImpl.java b/src/com/engine/dzfcd/service/impl/LeaveServiceImpl.java new file mode 100644 index 0000000..ca929b3 --- /dev/null +++ b/src/com/engine/dzfcd/service/impl/LeaveServiceImpl.java @@ -0,0 +1,73 @@ +package com.engine.dzfcd.service.impl; + +import com.engine.core.impl.Service; +import com.engine.kq.biz.KQLeaveRulesComInfo; +import com.wbi.util.Util; +import com.engine.dzfcd.service.LeaveService; +import com.engine.dzfcd.util.DzUtil; +import org.apache.commons.lang3.StringUtils; +import weaver.general.BaseBean; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class LeaveServiceImpl extends Service implements LeaveService { + + BaseBean bb = new BaseBean(); + @Override + public Map checkLeaveInt(Map params) { + + Map result = new HashMap<>(); + + bb.writeLog("params", params); + + String leaveType = Util.null2String(params.get("leaveType")); + bb.writeLog("leaveType", leaveType); + String resourceId = Util.null2String(params.get("resourceId")); + bb.writeLog("resourceId", resourceId); + + if (StringUtils.isBlank(leaveType)) { + result.put("code","500"); + result.put("msg","请先选择请假类型"); + return result; + } + + if (StringUtils.isBlank(resourceId)) { + result.put("code","500"); + result.put("msg","请先选择请假人员"); + return result; + } + + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + + //确认假期类型是否需要考虑前置假期余额 + DzUtil dzUtil = new DzUtil(); + List beforeLeaveTypes = dzUtil.getBeforeLeaveTypes(leaveType); + + if (beforeLeaveTypes != null && beforeLeaveTypes.size() > 0 ) { + for (String beforeLeave: beforeLeaveTypes) { + //获取假期余额 + Map getParams = new HashMap<>(); + getParams.put("newLeaveType", beforeLeave); + getParams.put("resourceId", resourceId); + Map vacationInfo = dzUtil.getVacationInfo(getParams, user); + if (vacationInfo.get("status").equals("1")) { + double doubleValue = Util.getDoubleValue(Util.null2String(vacationInfo.get("vacationInfo"))); + if (doubleValue > 0.00) { + result.put("code","500"); + result.put("msg",kqLeaveRulesComInfo.getLeaveName(beforeLeave) + "还有余额,请优先申请" + kqLeaveRulesComInfo.getLeaveName(beforeLeave)); + return result; + } + } + } + } + result.put("code","200"); + result.put("msg","可以申请"); + return result; + } + + + + +} diff --git a/src/com/engine/dzfcd/util/DzUtil.java b/src/com/engine/dzfcd/util/DzUtil.java new file mode 100644 index 0000000..596ebaf --- /dev/null +++ b/src/com/engine/dzfcd/util/DzUtil.java @@ -0,0 +1,173 @@ +package com.engine.dzfcd.util; + +import com.engine.kq.biz.KQBalanceOfLeaveBiz; +import com.engine.kq.biz.KQLeaveRulesBiz; +import com.engine.kq.biz.KQLeaveRulesComInfo; +import com.engine.kq.cmd.attendanceEvent.AttendanceUtil; +import com.engine.kq.wfset.util.SplitSelectSet; +import com.wbi.util.Util; +import org.apache.commons.lang3.StringUtils; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.BaseBean; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class DzUtil { + + /** + * 根据假期类型获取所有前置假期类型 + */ + public List getBeforeLeaveTypes(String leaveType){ + RecordSet rs = new RecordSet(); + List list = new ArrayList(); + if(StringUtils.isNotBlank(leaveType)){ + String sql = " select beforLeaveType from uf_leaveIntro where leaveType = "+leaveType; + rs.executeQuery(sql); + while (rs.next()){ + String id = Util.null2String(rs.getString("beforLeaveType")); + list.add(id); + addBeforeLeave(list,id); + } + } + + return list; + } + + public void addBeforeLeave(List datasList, String parentid){ + + String sql = " select beforLeaveType from uf_leaveIntro where leaveType="+parentid; + List> dataList = new ArrayList<>(); + RecordSet rs = new RecordSet(); + rs.execute(sql); + while(rs.next()){ + String id = Util.null2String(rs.getString("beforLeaveType")); + if(!datasList.contains(id)){ + datasList.add(id); + } + addBeforeLeave(datasList,id); + } + } + + /** + * 根据人员和假期类型查询假期余额 + */ + public Map getVacationInfo(Map params, User user) { + Map retmap = new HashMap(); + RecordSet rs = new RecordSet(); + String sql = ""; + String balanceOfLeave = ""; + try{ + //正式系统需要的 + String isFormal = weaver.general.Util.null2String(new BaseBean().getPropValue("kq_flow_formal", "isFormal"),"0"); + String newLeaveType = weaver.general.Util.null2String(params.get("newLeaveType")); + String resourceId = weaver.general.Util.null2String(params.get("resourceId")); + String fromDate = weaver.general.Util.null2String(params.get("fromDate")); + String fromTime = weaver.general.Util.null2String(params.get("fromTime")); + String toTime = weaver.general.Util.null2String(params.get("toTime")); + boolean balanceEnable = KQLeaveRulesBiz.getBalanceEnable(newLeaveType); + KQLeaveRulesComInfo leaveRulesComInfo = new KQLeaveRulesComInfo(); + boolean needClear = needClear(newLeaveType,leaveRulesComInfo,fromTime,toTime); + if(balanceEnable){ + if(fromDate.length() == 0){ + fromDate = DateUtil.getCurrentDate(); + } + if("1".equalsIgnoreCase(isFormal)){ + fromDate = DateUtil.getCurrentDate(); + } + balanceOfLeave = KQBalanceOfLeaveBiz.getRestAmount(resourceId, newLeaveType, fromDate); + String minimumUnit = leaveRulesComInfo.getMinimumUnit(newLeaveType); + + String minimumUnitName = KQLeaveRulesBiz.getMinimumUnitName(minimumUnit,user.getLanguage()); + String approvalInfo = ""; + double d_duration = AttendanceUtil.getFreezeDuration(newLeaveType,resourceId); + if(d_duration > 0){ + approvalInfo = "("+ SystemEnv.getHtmlLabelName(19134, user.getLanguage())+d_duration+minimumUnitName+")"; + } + retmap.put("vacationInfo",SystemEnv.getHtmlLabelName(10000809,weaver.general.Util.getIntValue(user.getLanguage()))+balanceOfLeave+minimumUnitName+approvalInfo); +// if(show_split_balance()){ + String vacationInfo = ""; + String allRestAmount = KQBalanceOfLeaveBiz.getRestAmount("" + resourceId, newLeaveType, fromDate, true); +// String currentRestAmount = KQBalanceOfLeaveBiz.getRestAmount("" + resourceId, newLeaveType, fromDate,false); + + double doubleValue = Util.getDoubleValue(Util.null2String(allRestAmount)); + vacationInfo = String.valueOf(doubleValue >= 0? doubleValue: 0.00 - d_duration); + retmap.put("vacationInfo",vacationInfo); +// } + retmap.put("status", "1"); + }else{ + //没有休假信息的 + retmap.put("status", "2"); + } + if(needClear){ + retmap.put("needClear", "1"); + }else{ + retmap.put("needClear", "0"); + } + + }catch (Exception e) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage())); + + } + return retmap; + } + + public boolean needClear(String newLeaveType, + KQLeaveRulesComInfo leaveRulesComInfo, String fromTime, String toTime) { + boolean needClear = false; + String minimumUnit = leaveRulesComInfo.getMinimumUnit(newLeaveType); + String timeselection = leaveRulesComInfo.getTimeSelection(newLeaveType); + + if(!"2".equalsIgnoreCase(timeselection)){ + if("2".equalsIgnoreCase(minimumUnit)){ + if(fromTime.equalsIgnoreCase(SplitSelectSet.forenoon_start) || fromTime.equalsIgnoreCase(SplitSelectSet.forenoon_end)){ + //表示不清空 + }else{ + needClear = true; + } + if(!needClear){ + if(toTime.equalsIgnoreCase(SplitSelectSet.afternoon_start) || toTime.equalsIgnoreCase(SplitSelectSet.afternoon_end)){ + //表示不清空 + }else{ + needClear = true; + } + } + }else if("4".equalsIgnoreCase(minimumUnit)){ + if(fromTime.equalsIgnoreCase(SplitSelectSet.daylong_start)){ + //表示不清空 + }else{ + needClear = true; + } + if(!needClear){ + if(toTime.equalsIgnoreCase(SplitSelectSet.daylong_end)){ + //表示不清空 + }else{ + needClear = true; + } + } + } + } + return needClear; + } + + /** + * 建模权限重构 + * @param billid_creator + * @param modeId + * @param billids + */ + public void modePerReconBatch(Map billid_creator, String modeId, List billids) { + ModeRightInfo ModeRightInfo = new ModeRightInfo(); + ModeRightInfo.setNewRight(true); + ModeRightInfo.editModeDataShare( billid_creator, Integer.parseInt(modeId), billids); + } + +} diff --git a/src/weaver/interfaces/dzfcd/job/SyncZkKqDataJob.java b/src/weaver/interfaces/dzfcd/job/SyncZkKqDataJob.java new file mode 100644 index 0000000..428efd7 --- /dev/null +++ b/src/weaver/interfaces/dzfcd/job/SyncZkKqDataJob.java @@ -0,0 +1,289 @@ +package weaver.interfaces.dzfcd.job; + +import cn.hutool.core.date.DateUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.engine.dzfcd.util.DzUtil; +import com.engine.kq.biz.KQFormatBiz; +import com.engine.kq.timer.KQQueue; +import com.engine.kq.timer.KQTaskBean; +import com.engine.kq.wfset.util.SplitActionUtil; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.jayway.jsonpath.Configuration; +import com.jayway.jsonpath.JsonPath; +import org.apache.commons.lang.StringUtils; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.*; + +import static weaver.interfaces.dzfcd.util.HttpsUtil.doPostJsonRequest; + + +/** + * Created with IntelliJ IDEA. + * 获取中控的考勤数据同步至OA + * @Auther: chenxu + * @Date: 2023/02/27/14:03 + * @Description: + */ +public class SyncZkKqDataJob extends BaseCronJob { + + private String startTime; + private String endTime; + + public String getStartTime() { + return startTime; + } + + public void setStartTime(String startTime) { + this.startTime = startTime; + } + + public String getEndTime() { + return endTime; + } + + public void setEndTime(String endTime) { + this.endTime = endTime; + } + + @Override + public void execute() { + new BaseBean(); + BaseBean bb = new BaseBean(); + bb.writeLog("获取中控的考勤数据同步至OA!!!"); + try { + DateTimeFormatter fdt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + //获取所有在职人员的id和workcode +// String workcodeField = bb.getPropValue("project_dzfcd", "workcode"); + Map idWorkcodeMap = new HashMap<>(); + RecordSet rs = new RecordSet(); + String acqResSql = "SELECT id, workcode FROM HRMRESOURCE " + + " WHERE status in (0,1,2,3)"; + bb.writeLog("acqResSql: " + acqResSql); + rs.executeQuery(acqResSql); + while (rs.next()){ + String userId = Util.null2String(rs.getString("id")); + String workcode = Util.null2String(rs.getString("workcode")); + if ( StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(workcode)) { + idWorkcodeMap.put(workcode,userId); + } + } + + //获取开始时间结束时间 + bb.writeLog("startTime = " + startTime); + bb.writeLog("endTime = " + endTime); + if (StringUtils.isBlank(startTime) || StringUtils.isNotBlank(endTime)) { + // 获取当前时间 + LocalDateTime now = LocalDateTime.now(); + endTime = now.format(fdt); + + // 获取两天前的时间 + LocalDateTime twoDaysAgo = now.minus(2, ChronoUnit.DAYS); + startTime = twoDaysAgo.format(fdt); + } + + bb.writeLog("startTime:"+startTime); + bb.writeLog("endTime:"+endTime); + String url = bb.getPropValue("project_dzfcd", "zkKqUrl"); + //获取日志表建模模块ID + String kqSyncLogModeId = bb.getPropValue("project_dzfcd","kqSyncLogModeId"); + bb.writeLog("url:"+url); + Map heads = new HashMap(); + Map dataMap = new HashMap(); + dataMap.put("starttime",startTime); + dataMap.put("endtime",endTime); + bb.writeLog("获取中控的考勤数据入参dataMap:"+JSONObject.toJSONString(dataMap)); + String back = doPostJsonRequest(url,heads, JSON.toJSONString(dataMap)); + bb.writeLog("urlBack:"+back); + bb.writeLog("获取中控的考勤数据--response:"+back); + List logParams = new ArrayList<>(); + List lsParams = new ArrayList<>(); + List lsFormatData = new ArrayList<>(); + Object tempBack = Configuration.defaultConfiguration().jsonProvider().parse(back); + Integer ret = JsonPath.read(tempBack, "$.ret"); + if ( ret == 0) { + Integer count = Util.getIntValue(Util.null2String(JsonPath.read(tempBack, "$.data.count").toString())); + if ( count > 0 ) { + List> items = JsonPath.read(tempBack, "$.data.items[*]"); + for (Map item : items) { + String pin = Util.null2String(item.get("pin")); + String checktime = Util.null2String(item.get("checktime")); + String alias = Util.null2String(item.get("alias")); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date date = df.parse(checktime); + DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd"); + DateFormat df3 = new SimpleDateFormat("HH:mm:ss"); + Integer isimport = 1; + String userid = Util.null2String(idWorkcodeMap.get(pin)); + Integer usertype = 1; + String signDate = df2.format(date); + String signTime = df3.format(date); + Integer isincom = 1; + String signfrom = "OutDataSourceSyn"; + if (StringUtils.isBlank(alias)) { + bb.writeLog("--item:"+item); + } + String addr = alias; + List params = new ArrayList<>(); + if (StringUtils.isBlank(userid)) { + continue; + } + params.add(userid); + params.add(usertype); + params.add(signDate); + params.add(signTime); + params.add(""); + params.add(isincom); + params.add(isimport); + params.add(signfrom); + params.add(""); + params.add(""); + params.add(addr); + params.add("中控考勤机"); + lsParams.add(params); + String formatData = userid + "|" + signDate + "|" + signTime; + if (!lsFormatData.contains(formatData)) { + lsFormatData.add(formatData); + } + //日志表 + List logPa = new ArrayList<>(); + logPa.add(signDate); + logPa.add(userid); + logPa.add(signDate); + logPa.add(signTime); + logPa.add(addr); + logPa.add(kqSyncLogModeId); + logPa.add("1"); + logPa.add("0"); + logPa.add(signDate); + logPa.add(endTime.substring(10,16)); + logParams.add(logPa); + + } + } + } + bb.writeLog("lsParams:"+JSON.toJSONString(lsParams)); + bb.writeLog("lsFormatData:"+JSON.toJSONString(lsFormatData)); + + Map> overtimeMap = Maps.newHashMap(); + List overtimeList = Lists.newArrayList(); + List formatParams = null; + List> lsFormatParams = new ArrayList<>(); + List delParams = null; + List lsDelParams = new ArrayList<>(); + + bb.writeLog("准备刷新报表数据"); + //刷新报表数据 + for(int i=0;lsFormatData!=null&&i(); + String[] formatData = Util.splitString(lsFormatData.get(i),"|"); + String date_1 = weaver.common.DateUtil.addDate(formatData[1], -1); + formatParams.add(formatData[0]); + formatParams.add(date_1); + lsFormatParams.add(formatParams); + + formatParams = new ArrayList<>(); + formatParams.add(formatData[0]); + formatParams.add(formatData[1]); + lsFormatParams.add(formatParams); + + delParams = new ArrayList<>(); + delParams.add(formatData[0]); + delParams.add(formatData[1]); + delParams.add(formatData[2]); + lsDelParams.add(delParams); + + String resourceId = formatData[0]; + String kqdate = formatData[1]; + if(overtimeMap.containsKey(resourceId)){ + List tmp_overtimeList = overtimeMap.get(resourceId); + if(!tmp_overtimeList.contains(kqdate)){ + tmp_overtimeList.add(kqdate); + } + }else{ + if(!overtimeList.contains(kqdate)){ + overtimeList.add(kqdate); + } + overtimeMap.put(resourceId, overtimeList); + } + } + + String sql = ""; + RecordSet rsB = new RecordSet(); + bb.writeLog("开始同步数据"); + + //记录日志 + //获取插入前最大的ID + Integer maxId = -1; + String acqMaxId = "select MAX(id) as id from uf_kqsynclog order by id desc"; + rsB.executeQuery(acqMaxId); + while (rsB.next()) { + maxId = Util.getIntValue(Util.null2String(rsB.getString("id"))); + } + + String addLogSql = "insert into uf_kqsynclog (syncdate, resourceid, kqdate, kqtime, kqalias, " + + " formmodeid, modedatacreater, modedatacreatertype, modedatacreatedate, modedatacreatetime) " + + " values (?,?,?,?,?,?,?,?,?,?)"; + boolean bLog = rsB.executeBatchSql(addLogSql, logParams); + bb.writeLog("bLog: " + bLog); + if (bLog) { + List billids = new ArrayList<>(); + Map billid_creator = new HashMap<>(); + String acqBillidsSql = "select id from uf_kqsynclog where id > ?"; + rsB.executeQuery(acqBillidsSql, maxId); + while (rsB.next()) { + Integer id = Util.getIntValue(Util.null2String(rsB.getString("id"))); + billids.add(id); + billid_creator.put(id, 1); + } + if (billids != null && billids.size() > 0) { + DzUtil dzUtil = new DzUtil(); + dzUtil.modePerReconBatch(billid_creator, kqSyncLogModeId, billids); + } + } + + //删除本次同步数据 + bb.writeLog("lsDelParams: " + lsDelParams); + sql = " delete from hrmschedulesign where signfrom='OutDataSourceSyn' and userid =? and signdate = ? and signtime = ? "; + boolean b1 = rsB.executeBatchSql(sql, lsDelParams); + bb.writeLog("b1: " + b1); + + sql = " insert into HrmScheduleSign (userid, usertype, signdate, signtime, clientaddress, isincom, isimport, signfrom, longitude, latitude, addr,memo) " + + " values(?,?,?,?,?,?,?,?,?,?,?,?)"; + boolean b2 = rsB.executeBatchSql(sql, lsParams); + bb.writeLog("b2: " + b2); + + new KQFormatBiz().format(lsFormatParams); + + bb.writeLog("开始处理加班生成"); + //处理加班生成 + List tasks = new ArrayList<>(); + for(Map.Entry> mme: overtimeMap.entrySet()){ + String resid = mme.getKey(); + List overList = mme.getValue(); + for(String date : overList){ + SplitActionUtil.pushOverTimeTasks(date,date,resid,tasks); + } + } + if(!tasks.isEmpty()){ + KQQueue.writeTasks(tasks); + } + + } catch (Exception e) { + e.printStackTrace(); + bb.writeLog(e); + bb.writeLog("获取中控的考勤数据同步至OA--error"+e.getMessage()); + } + } + +} diff --git a/src/weaver/interfaces/dzfcd/util/HttpsUtil.java b/src/weaver/interfaces/dzfcd/util/HttpsUtil.java new file mode 100644 index 0000000..85d193b --- /dev/null +++ b/src/weaver/interfaces/dzfcd/util/HttpsUtil.java @@ -0,0 +1,271 @@ +package weaver.interfaces.dzfcd.util; + + +import org.apache.commons.collections.MapUtils; +import org.apache.http.Consts; +import org.apache.http.HttpEntity; +import org.apache.http.NameValuePair; +import org.apache.http.StatusLine; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.*; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.HttpClientConnectionManager; +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.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntityBuilder; +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.PoolingHttpClientConnectionManager; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.protocol.HTTP; +import org.apache.http.util.EntityUtils; +import org.springframework.web.multipart.MultipartFile; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.io.IOException; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + + +public class HttpsUtil { + + private static CloseableHttpClient httpclient = HttpClientBuilder.create().setConnectionManager(poolingConnectionManager()).build(); + + public static HttpClientConnectionManager poolingConnectionManager() { + PoolingHttpClientConnectionManager poolingConnectionManager = new PoolingHttpClientConnectionManager(); + // 连接池最大连接数 + poolingConnectionManager.setMaxTotal(1000); + // 每个主机的并发 + poolingConnectionManager.setDefaultMaxPerRoute(100); + return poolingConnectionManager; + } + + private static RequestConfig requestConfig = RequestConfig.custom() + .setConnectTimeout(1000) + // 从连接池中获取到连接的最长时间 + .setConnectionRequestTimeout(500) + // 数据传输的最长时间,联合差补需要同步较长时间 + .setSocketTimeout(60000) + .build(); + + + private static void prepareHeaders(HttpRequestBase httpRequest, Map headers) { + if (!MapUtils.isEmpty(headers)) { + for (Map.Entry entry : headers.entrySet()) { + httpRequest.addHeader(entry.getKey(), entry.getValue()); + } + } + } + + private static String sendRequest(HttpRequestBase httpRequest) throws IOException { + String result = null; + CloseableHttpClient httpclient = creteClient(); + try (CloseableHttpResponse resp = httpclient.execute(httpRequest)) { + HttpEntity entity = resp.getEntity(); + result = (entity == null ? null : EntityUtils.toString(entity, Consts.UTF_8)); + StatusLine statusLine = resp.getStatusLine(); + if (statusLine.getStatusCode() >= 300) { + EntityUtils.consume(entity); +// String errorMsg = Strings.lenientFormat("Http status abnormal-status code is %s, response is %s", resp.getStatusLine().getStatusCode(), result); + } + } + return result; + } + + public static String doPostJsonRequest(String url, Map headers, String jsonStr) throws IOException { + HttpPost httpost = new HttpPost(url); + prepareHeaders(httpost, headers); + StringEntity entity = new StringEntity(jsonStr, Consts.UTF_8); +// entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + httpost.setEntity(entity); + return sendRequest(httpost); + } + + public static String doGet(String url, Map headers) throws IOException { + HttpGet httpget = new HttpGet(url); + prepareHeaders(httpget, headers); + return sendRequest(httpget); + } + + public static String doPost(String url, Map headers, Map params) throws IOException { + HttpPost httpost = new HttpPost(url); + prepareHeaders(httpost, headers); + //组织请求参数 + List paramList = new ArrayList(); + if (params != null && params.size() > 0) { + Set keySet = params.keySet(); + for (String key : keySet) { + paramList.add(new BasicNameValuePair(key, params.get(key))); + } + } + UrlEncodedFormEntity entity = new UrlEncodedFormEntity((Iterable) paramList, Consts.UTF_8); + entity.setContentType("application/x-www-form-urlencoded"); + httpost.setEntity(entity); + return sendRequest(httpost); + } + + + public static byte[] doGetWithByteArrayResp(String url, Map headers) throws IOException { + HttpGet httpGet = new HttpGet(url); + httpGet.setConfig(requestConfig); + prepareHeaders(httpGet, headers); + return sendRequestWithByteArrayResp(httpGet); + } + + + + private static byte[] sendRequestWithByteArrayResp(HttpRequestBase httpRequest) throws IOException { + httpRequest.addHeader(HTTP.CONTENT_ENCODING, "UTF-8"); + byte[] result = null; + CloseableHttpClient httpclient = creteClient(); + try (CloseableHttpResponse resp = httpclient.execute(httpRequest)) { + HttpEntity entity = resp.getEntity(); + result = (entity == null ? null : EntityUtils.toByteArray(entity)); +// StatusLine statusLine = resp.getStatusLine(); +// if (statusLine.getStatusCode() >= 300) { +// EntityUtils.consume(entity); +// String errorMsg = Strings.lenientFormat("Http status abnormal-status code is %s, response is %s", resp.getStatusLine().getStatusCode(), result); +// throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); +// } + } + return result; + } + + + /** + * 文件上传 + * + * @param url 请求路径 + * @param headers 请求头部 + * @param params 请求参数 + * @param files 附件 + * @param requestFileName 附件接受名称 + * @return + * @throws IOException + */ + public static String doPostFormMultipart(String url, Map headers, Map params, List files, String requestFileName) throws IOException { + HttpPost httpost = new HttpPost(url); + prepareHeaders(httpost, headers); + //组织请求参数 + if (params != null && params.size() > 0) { + List paramList = new ArrayList(); + Set keySet = params.keySet(); + for (String key : keySet) { + paramList.add(new BasicNameValuePair(key, params.get(key))); + } + } + MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create(); + mEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); + mEntityBuilder.setCharset(Consts.UTF_8); + + // 普通参数 + ContentType contentType = ContentType.create("text/plain", Consts.UTF_8);//解决中文乱码 + if (params != null && params.size() > 0) { + Set keySet = params.keySet(); + for (String key : keySet) { + mEntityBuilder.addTextBody(key, params.get(key), contentType); + } + } + //二进制参数 + if (files != null && files.size() > 0) { + for (MultipartFile file : files) { + mEntityBuilder.addBinaryBody(requestFileName, file.getInputStream(), ContentType.create("multipart/form-data", Consts.UTF_8), file.getName()); + } + } + httpost.setEntity(mEntityBuilder.build()); + return sendRequest(httpost); + } + + + public static String doPutJsonRequest(String url, Map headers, String jsonStr) throws IOException { + HttpPut httpPut = new HttpPut(url); + prepareHeaders(httpPut, headers); + StringEntity entity = new StringEntity(jsonStr, Consts.UTF_8); + entity.setContentType("application/json"); + httpPut.setEntity(entity); + return sendRequest(httpPut); + } + + + public static String doDelete(String url, Map headers) throws IOException { + HttpDelete httpDelete = new HttpDelete(url); + prepareHeaders(httpDelete, headers); + return sendRequest(httpDelete); + + } + + + /** + * 绕过验证 + * + * @return + * @throws NoSuchAlgorithmException + * @throws KeyManagementException + */ + public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException { + SSLContext sc = SSLContext.getInstance("SSLv3"); + + // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法 + X509TrustManager trustManager = new X509TrustManager() { + @Override + public void checkClientTrusted( + java.security.cert.X509Certificate[] paramArrayOfX509Certificate, + String paramString) throws CertificateException { + } + + @Override + public void checkServerTrusted( + java.security.cert.X509Certificate[] paramArrayOfX509Certificate, + String paramString) throws CertificateException { + } + + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + }; + + sc.init(null, new TrustManager[]{trustManager}, null); + return sc; + } + + + public static CloseableHttpClient creteClient() { + //采用绕过验证的方式处理https请求 + try { + SSLContext sslcontext = createIgnoreVerifySSL(); + // 设置协议http和https对应的处理socket链接工厂的对象 + Registry socketFactoryRegistry = RegistryBuilder.create() + .register("http", PlainConnectionSocketFactory.INSTANCE) + .register("https", new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE)) + .build(); + PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); + HttpClients.custom().setConnectionManager(connManager); + + //创建自定义的httpclient对象 + CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build(); + return client; + } catch (Exception e) { + return null; + } + + } + + +}