This commit is contained in:
zhangxinah@yonyou.com 2025-03-26 15:39:21 +08:00
commit bd1d286e2a
7 changed files with 2392 additions and 0 deletions

View File

@ -0,0 +1,339 @@
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package nc.bs.mmpub.setanalysis.bp.multistorey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.mmpub.setanalysis.bp.SaMonolayerBP;
import nc.bs.mmpub.setanalysis.bp.demand.SaDemandInsertBP;
import nc.bs.mmpub.setanalysis.bp.demand.SaDemandQueryBP;
import nc.bs.mmpub.setanalysis.bp.log.SaLogInsertBP;
import nc.bs.mmpub.setanalysis.bp.utils.SaArrayUtil;
import nc.bs.mmpub.setanalysis.bp.utils.SaBooleanUtils;
import nc.bs.mmpub.setanalysis.bp.utils.SaLogger;
import nc.bs.mmpub.setanalysis.bp.utils.SaVOUtils;
import nc.impl.pubapp.pattern.data.vo.VOUpdate;
import nc.impl.pubapp.pattern.data.vo.VOUpdateTS;
import nc.util.mmf.framework.base.MMNumberUtil;
import nc.util.mmf.framework.base.MMValueCheck;
import nc.vo.mmpub.setanalysis.entity.AggAnalysisVO;
import nc.vo.mmpub.setanalysis.entity.SaAnalysisVO;
import nc.vo.mmpub.setanalysis.entity.SaContext;
import nc.vo.mmpub.setanalysis.entity.SaDemandVO;
import nc.vo.mmpub.setanalysis.entity.SaMatchVO;
import nc.vo.mmpub.setanalysis.enumeration.SaDemandType;
import nc.vo.mmpub.setanalysis.enumeration.SaMatchType;
import nc.vo.mmpub.setanalysis.utils.SaMeasureUtil;
import nc.vo.mmpub.setanalysis.utils.SaValidateUtil;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.pub.MapList;
import nc.vo.pubapp.pattern.pub.MathTool;
import nccloud.baseapp.core.log.NCCForUAPLogger;
/**
* 齐套率回写流程生产订单
* 2005适配2312
*
* @author mzr
* @date 2025/3/26
*/
public class SaMultiStoreyBP {
private SaContext sc;
private List<SaMatchVO> smVO;
private MapList<String, SaDemandVO> demand;
private Map<String, SaDemandVO> demandPkMap;
private Map<String, AggAnalysisVO> aggPkMap;
private int maxLevel = 0;
private SaAlgorithmBP algorithm;
public SaMultiStoreyBP(SaContext sc) {
SaLogger.debug("3.1.反算齐套初始化开始");
this.algorithm = new SaAlgorithmBP();
this.setSc(sc);
List<SaDemandVO> sdList = SaVOUtils.getDemandList(sc.getSdVO());
this.maxLevel = SaDemandQueryBP.getMaxLevelCode(sdList);
this.setDemand(SaVOUtils.getSortMapList(sdList, "levelcode"));
if (!MMValueCheck.isEmpty(sc.getSdVO())) {
sc.getSdVO().toMap().clear();
}
this.smVO = new ArrayList();
this.demandPkMap = new HashMap();
this.demandPkMap = this.algorithm.demandGroupForPk(sdList);
this.aggPkMap = new HashMap();
this.aggPkMap = this.algorithm.aggGroupForPk(this.sc.getAggs());
}
public void doMultiStorey() {
SaLogger.debug("3.2.反算齐套开始计算");
if (!MMValueCheck.isEmpty(this.demand)) {
for(int curLevel = this.maxLevel; curLevel > 0; --curLevel) {
List<SaDemandVO> sdList = this.demand.get(Integer.toString(curLevel));
if (!MMValueCheck.isEmpty(sdList)) {
for(SaDemandVO sa : sdList) {
this.algorithm.setNum(sa);
}
this.setDemandForAnalysis(sdList, Integer.toString(curLevel));
SaLogger.debug("3.3.反算齐套层码" + Integer.toString(curLevel));
}
}
}
this.insert();
}
private void setDemandForAnalysis(List<SaDemandVO> sdList, String key) {
if (!MMValueCheck.isEmpty(sdList)) {
MapList<String, SaDemandVO> demandMap = SaVOUtils.getSortMapList(sdList, "pk_analysis");
if (!MMValueCheck.isEmpty(demandMap)) {
for(Map.Entry<String, List<SaDemandVO>> entry : demandMap.toMap().entrySet()) {
List<SaDemandVO> demandList = (List)entry.getValue();
this.setDemandForFatherid(demandList, key);
}
}
}
}
private void setDemandForFatherid(List<SaDemandVO> sdList, String key) {
if (!MMValueCheck.isEmpty(sdList)) {
MapList<String, SaDemandVO> demandMap = SaVOUtils.getSortMapList(sdList, "vfatherid");
if (!MMValueCheck.isEmpty(demandMap)) {
for(Map.Entry<String, List<SaDemandVO>> entry : demandMap.toMap().entrySet()) {
List<SaDemandVO> demandList = SaArrayUtil.getMultiDemandSort((List)entry.getValue());
SaDemandVO nsetsnum = new SaDemandVO();
if (MMValueCheck.isNotEmpty(demandList)) {
if (SaBooleanUtils.isReplace(demandList)) {
SaRaplaceItemBP raplaceBP = new SaRaplaceItemBP(demandList);
List<SaDemandVO> raplaceList = raplaceBP.getRaplaceItem();
List<SaDemandVO> materialList = raplaceBP.getMaterialItem();
if (!MMValueCheck.isEmpty(raplaceList)) {
nsetsnum = this.algorithm.getReplaceNum(raplaceList);
}
new SaDemandVO();
if (!MMValueCheck.isEmpty(raplaceList)) {
SaDemandVO material = this.setMatchFatherid(materialList, key);
if (!MMValueCheck.isEmpty(material)) {
nsetsnum.setNsetsnum(nsetsnum.getNsetsnum().add(material.getNsetsnum()));
}
}
} else {
nsetsnum = this.setMatchFatherid(demandList, key);
}
}
if (MMValueCheck.isNotEmpty(nsetsnum.getNsetsnum()) && nsetsnum.getNsetsnum().compareTo(UFDouble.ZERO_DBL) > 0 || MMValueCheck.isNotEmpty(nsetsnum.getNreplacesetsnum()) && nsetsnum.getNreplacesetsnum().compareTo(UFDouble.ZERO_DBL) > 0) {
this.setRewriteNmaterialnum(key, nsetsnum, false);
}
}
}
}
}
private SaDemandVO setMatchFatherid(List<SaDemandVO> sdList, String key) {
if (MMValueCheck.isEmpty(sdList)) {
return null;
} else {
UFDouble nsetsnumsum = new UFDouble();
SaDemandVO nsetsnum = new SaDemandVO();
int num = (int) sdList.stream()
.filter(saDemandVO -> MathTool.compareTo(saDemandVO.getNmaterialnum(), saDemandVO.getNdemandnum()) >= 0)
.count();
MapList<String, SaDemandVO> demandMap = SaVOUtils.getSortMapList(sdList, "vmatchfatherid");
if (!MMValueCheck.isEmpty(demandMap)) {
for(Map.Entry<String, List<SaDemandVO>> entry : demandMap.toMap().entrySet()) {
List<SaDemandVO> demandList = (List)entry.getValue();
if (((SaDemandVO)demandList.get(0)).getFmatchtype().equals(SaMatchType.PD.toIntValue()) && ((SaDemandVO)demandList.get(0)).getFdemandtype().equals(SaDemandType.NR.toIntValue())) {
nsetsnum = this.algorithm.minDemand((SaDemandVO[])demandList.toArray(new SaDemandVO[0]));
// 设置物料的总行数满足齐套的物料的行数
nsetsnum.setGoodsnum(new UFDouble(sdList.size()));
nsetsnum.setPass_goodsnum(new UFDouble(num));
this.setRewriteNmaterialnum(key, nsetsnum, false);
this.setRewriteNmaterialnum(key, nsetsnum, true);
nsetsnumsum = nsetsnumsum.add(nsetsnum.getNsetsnum());
break;
}
}
for(Map.Entry<String, List<SaDemandVO>> entry : demandMap.toMap().entrySet()) {
List<SaDemandVO> demandList = (List)entry.getValue();
if (!((SaDemandVO)demandList.get(0)).getFdemandtype().equals(SaDemandType.NR.toIntValue()) && demandList.size() > 0) {
nsetsnum = this.algorithm.minDemand((SaDemandVO[])demandList.toArray(new SaDemandVO[0]));
// 设置物料的总行数满足齐套的物料的行数
nsetsnum.setGoodsnum(new UFDouble(sdList.size()));
nsetsnum.setPass_goodsnum(new UFDouble(num));
this.setRewriteNmaterialnum(key, nsetsnum, true);
nsetsnumsum = SaValidateUtil.add(nsetsnumsum, nsetsnum.getNsetsnum());
}
}
}
if (!MMValueCheck.isEmpty(nsetsnumsum)) {
nsetsnum.setNsetsnum(nsetsnumsum);
}
return nsetsnum;
}
}
private void setRewriteNmaterialnum(String key, SaDemandVO nsetsnum, boolean isUpdateMatch) {
if (!MMValueCheck.isEmpty(nsetsnum)) {
int level = this.getLevel(key);
if (level == 0) {
if (this.aggPkMap != null) {
AggAnalysisVO agg = (AggAnalysisVO)this.aggPkMap.get(nsetsnum.getVfatherid());
if (agg != null) {
SaAnalysisVO analysis = agg.getParentVO();
analysis.setNsetsnum(MMNumberUtil.add(new UFDouble[]{nsetsnum.getNsetsnum(), nsetsnum.getNreplacesetsnum()}));
if (isUpdateMatch) {
// 流程生产订单表体主键
String cdemandbillbid = analysis.getCdemandbillbid();
// 物料的总行数
UFDouble goodsnum = nsetsnum.getGoodsnum().setScale(2, UFDouble.ROUND_HALF_UP);
// 满足齐套的物料的行数
UFDouble pass_goodsnum = nsetsnum.getPass_goodsnum().setScale(2, UFDouble.ROUND_HALF_UP);
// 齐套率计算=满足的/总数量
UFDouble rate = pass_goodsnum.div(goodsnum, 2, UFDouble.ROUND_HALF_UP);
// 修改流程生产订单的齐套率物料的总行数满足齐套的物料的行数
String sql = String.format("update mm_mo set vdef12 = '%s',vdef11 = '%s',vdef4 = '%s' where cmoid = '%s'",
goodsnum, pass_goodsnum, rate.toString(), cdemandbillbid);
updateDef4(sql);
}
}
}
} else if (this.demandPkMap != null) {
new SaDemandVO();
SaDemandVO var7 = (SaDemandVO)this.demandPkMap.get(nsetsnum.getVfatherid());
if (!isUpdateMatch) {
UFDouble nmatch = MMNumberUtil.add(new UFDouble[]{var7.getNmatchnum(), nsetsnum.getNsetsnum()});
var7.setNmaterialnum(nmatch);
var7.setNreplacesetsnum(nsetsnum.getNreplacesetsnum());
} else {
this.updateNmaterialnum(nsetsnum, var7);
}
}
}
}
private int updateDef4(String sql) {
try {
NCCForUAPLogger.debug("sql = " + sql);
BaseDAO baseDAO = new BaseDAO();
return baseDAO.executeUpdate(sql);
} catch (DAOException e) {
NCCForUAPLogger.debug("setRewriteNmaterialnum-exp:" + e.getMessage());
throw new RuntimeException(e);
}
}
private int getLevel(String key) {
return key.length() == 0 ? 0 : Integer.parseInt(key) - 1;
}
private void insert() {
(new SaLogInsertBP(this.sc)).insertLog();
SaDemandInsertBP sdi = new SaDemandInsertBP();
List<SaDemandVO> sdList = SaVOUtils.getDemandList(this.demand);
if (!MMValueCheck.isEmpty(sdList)) {
SaLogger.debug("3.4.反算持久化(相关需求,分析对象)" + sdList.size());
sdi.insertDemand((SaDemandVO[])sdList.toArray(new SaDemandVO[0]), this.sc);
SaAnalysisVO[] sas = SaVOUtils.construcVOs(this.getSc().getAggs());
SaMeasureUtil.setAnalysisNum(sas);
VOUpdate<SaAnalysisVO> voup = new VOUpdate();
voup.update(sas, new String[]{"nsetsnum", "nremainnum", "nsetsasnum", "nassremainnum"});
this.updateMatch();
SaLogger.debug("3.5.反算持久化结束");
}
}
private void updateNmaterialnum(SaDemandVO saDemand, SaDemandVO hDemand) {
if (!saDemand.getVfatherid().equals(saDemand.getVmatchfatherid()) && (saDemand.getFmatchtype().equals(SaMatchType.PICK.value()) || saDemand.getFmatchtype().equals(SaMatchType.PD.value()) || saDemand.getFmatchtype().equals(SaMatchType.MREQ.value()))) {
SaMatchVO sm = new SaMatchVO();
sm.setPk_match(saDemand.getVmatchfatherid());
sm.setNmaterialnum(saDemand.getNsetsnum());
UFDouble nsetsnum = SaMonolayerBP.getNsetsnum(hDemand, saDemand.getNsetsnum(), (UFDouble)null);
sm.setNsetsnum(nsetsnum);
this.getSmVO().add(sm);
}
}
private void updateMatch() {
SaMatchVO[] sms = (SaMatchVO[])this.getSmVO().toArray(new SaMatchVO[0]);
if (!MMValueCheck.isEmpty(sms)) {
VOUpdateTS<SaMatchVO> voQuery = new VOUpdateTS();
voQuery.update(sms);
VOUpdate<SaMatchVO> voup = new VOUpdate();
voup.update(sms, new String[]{"nmaterialnum", "nsetsnum"});
}
}
public int getMaxLevel() {
return this.maxLevel;
}
public void setMaxLevel(int maxLevel) {
this.maxLevel = maxLevel;
}
public MapList<String, SaDemandVO> getDemand() {
return this.demand;
}
public void setDemand(MapList<String, SaDemandVO> demand) {
this.demand = demand;
}
public SaContext getSc() {
return this.sc;
}
public void setSc(SaContext sc) {
this.sc = sc;
}
public List<SaMatchVO> getSmVO() {
return this.smVO;
}
public void setSmVO(List<SaMatchVO> smVO) {
this.smVO = smVO;
}
public SaAlgorithmBP getAlgorithm() {
return this.algorithm;
}
public void setAlgorithm(SaAlgorithmBP algorithm) {
this.algorithm = algorithm;
}
public Map<String, SaDemandVO> getDemandPkMap() {
return this.demandPkMap;
}
public void setDemandPkMap(Map<String, SaDemandVO> demandPkMap) {
this.demandPkMap = demandPkMap;
}
public Map<String, AggAnalysisVO> getAggPkMap() {
return this.aggPkMap;
}
public void setAggPkMap(Map<String, AggAnalysisVO> aggPkMap) {
this.aggPkMap = aggPkMap;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,65 @@
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package nc.bs.so.m32.maintain;
import nc.bs.scmpub.rule.VOSagaFrozenValidateRule;
import nc.bs.scmpub.ssc.rule.BaseBillDeleteSyncImage;
import nc.bs.scmpub.ssc.rule.SyncRPBillRuleForDelete;
import nc.bs.so.m32.maintain.rule.delete.*;
import nc.bs.so.m32.plugin.BP32PlugInPoint;
import nc.impl.pubapp.pattern.data.bill.BillDelete;
import nc.impl.pubapp.pattern.rule.IRule;
import nc.impl.pubapp.pattern.rule.processer.AroundProcesser;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pubapp.pattern.log.TimeLog;
import nc.vo.scmpub.res.billtype.SOBillType;
import nc.vo.so.m32.entity.SaleInvoiceVO;
public class DeleteSaleInvoiceBP {
public DeleteSaleInvoiceBP() {
}
public void delete(SaleInvoiceVO[] bills) {
AroundProcesser<SaleInvoiceVO> processer = new AroundProcesser(BP32PlugInPoint.DeleteAction);
this.addBeforeRule(processer);
this.addAfterRule(processer);
TimeLog.logStart();
processer.before(bills);
TimeLog.info(NCLangRes4VoTransl.getNCLangRes().getStrByID("4006008_0", "04006008-0020"));
TimeLog.logStart();
BillDelete<SaleInvoiceVO> bo = new BillDelete();
bo.delete(bills);
TimeLog.info(NCLangRes4VoTransl.getNCLangRes().getStrByID("4006008_0", "04006008-0021"));
TimeLog.logStart();
processer.after(bills);
TimeLog.info(NCLangRes4VoTransl.getNCLangRes().getStrByID("4006008_0", "04006008-0022"));
}
private void addAfterRule(AroundProcesser<SaleInvoiceVO> processer) {
IRule<SaleInvoiceVO> rule = new ReturnBillCodeRule();
processer.addAfterRule(rule);
IRule<SaleInvoiceVO> updateOppDeleteRule = new UpdateOppDeleteRule();
processer.addAfterRule(updateOppDeleteRule);
IRule<SaleInvoiceVO> rewriteARSubDeleteRule = new RewriteARSubDeleteRule();
processer.addAfterRule(rewriteARSubDeleteRule);
IRule<SaleInvoiceVO> rewriteBillDeleteRule = new RewriteBillDeleteRule();
processer.addAfterRule(rewriteBillDeleteRule);
IRule<SaleInvoiceVO> baseBillDeleteSyncImage = new BaseBillDeleteSyncImage();
processer.addAfterRule(baseBillDeleteSyncImage);
IRule<SaleInvoiceVO> syncRPBillRuleForDelete = new SyncRPBillRuleForDelete(SOBillType.Invoice.getCode());
processer.addAfterRule(syncRPBillRuleForDelete);
// 删除后同步修改BIP的开票申请存的NCC信息
IRule<SaleInvoiceVO> syncBipBillRuleForDelete = new SyncBipBillRuleForDelete();
processer.addAfterRule(syncBipBillRuleForDelete);
}
private void addBeforeRule(AroundProcesser<SaleInvoiceVO> processer) {
IRule<SaleInvoiceVO> rule = new VOSagaFrozenValidateRule(true);
processer.addBeforeRule(rule);
IRule<SaleInvoiceVO> checkEnableDeleteRule = new CheckEnableDeleteRule();
processer.addBeforeRule(checkEnableDeleteRule);
}
}

View File

@ -0,0 +1,203 @@
package nc.bs.so.m32.maintain.rule.delete;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.yonyou.cloud.utils.StringUtils;
import nc.bs.logging.Logger;
import nc.bs.uapbd.util.IgnoreSslUtil;
import nc.impl.pubapp.pattern.rule.IRule;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.so.m32.entity.SaleInvoiceBVO;
import nc.vo.so.m32.entity.SaleInvoiceHVO;
import nc.vo.so.m32.entity.SaleInvoiceVO;
import nccloud.baseapp.core.log.NCCForUAPLogger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
/**
* 删除后同步修改BIP的开票申请存的NCC信息
* 2005适配2312
*
* @author mzr
* @date 2025/3/20
*/
public class SyncBipBillRuleForDelete implements IRule<SaleInvoiceVO> {
private static String appKey = "a3c57e0d871240e9b9bf56b35001a324";
private static String appSecret = "a959f7786db8dbb9a2c0493b5855a46bea68ad75";
private static String tokenUrl = "https://www.tkkfbip.com/iuap-api-auth/open-auth/selfAppAuth/getAccessToken";
private static String toBipUrl = "https://www.tkkfbip.com/iuap-api-gateway/oxp4h3x6/current_yonbip_default_sys/KKAPI/invoiceApplication/updateInvoice?access_token=";
@Override
public void process(SaleInvoiceVO[] vos) {
try {
boolean hasVdef38 = Arrays.stream(vos)
.map(SaleInvoiceVO::getParentVO)
.anyMatch(hvo -> StringUtils.isNotEmpty(hvo.getVdef38()));
// 如果vos里边都没有存BIP合同的开票申请的主键则不往下执行
if (!hasVdef38) {
return;
}
String access_token = getAccessToken();
for (SaleInvoiceVO invoiceVO : vos) {
SaleInvoiceHVO hvo = invoiceVO.getParentVO();
SaleInvoiceBVO[] bvos = invoiceVO.getChildrenVO();
if (access_token.isEmpty()) {
Logger.error("SyncBipBillRuleForDelete-token获取失败");
ExceptionUtils.wrappBusinessException("token获取失败");
}
// bip旗舰版发票主键
String vdef38 = hvo.getVdef38();
Logger.error("SyncBipBillRuleForDelete-vdef38 = " + vdef38);
if (StringUtils.isNotEmpty(vdef38)) {
List<JSONObject> childrenList = new ArrayList<>();
for (SaleInvoiceBVO bvo : bvos) {
JSONObject jsonObject = new JSONObject();
if (StringUtils.isNotEmpty(bvo.getVbdef14())) {
jsonObject.put("id", bvo.getVbdef14());
jsonObject.put("saleInvoiceDetailId", "");
childrenList.add(jsonObject);
}
}
JSONObject updateJson = new JSONObject();
updateJson.put("id", vdef38);
updateJson.put("saleInvoiceId", "");
updateJson.put("contractInvoiceApplicationDetailList", childrenList);
String bipRes = doPost(toBipUrl + access_token, updateJson);
NCCForUAPLogger.debug("SyncBipBillRuleForDelete-bipRes = " + bipRes);
}
}
} catch (NoSuchAlgorithmException | InvalidKeyException | IOException e) {
Logger.error("SyncBipBillRuleForDelete-exp:" + e.getMessage(), e);
}
}
/**
* 获取旗舰版的token
*
* @return token
* @author mzr
* @date 2025/3/20
*/
private String getAccessToken() throws NoSuchAlgorithmException, InvalidKeyException, IOException {
// 获取旗舰版的token
Map<String, String> params = new HashMap<>();
// 除签名外的其他参数
params.put("appKey", appKey);
String timestamp = String.valueOf(System.currentTimeMillis());
params.put("timestamp", timestamp);
// 计算签名
Map<String, String> treeMap = new TreeMap<>(params);
StringBuilder stringBuilder = new StringBuilder();
for (Map.Entry<String, String> entry : treeMap.entrySet()) {
stringBuilder.append(entry.getKey()).append(entry.getValue());
}
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(appSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] signData = mac.doFinal(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
String base64String = Base64.getEncoder().encodeToString(signData);
String signature = URLEncoder.encode(base64String, "UTF-8");
params.put("signature", signature);
String responseString = doGet(tokenUrl, params);
Gson gson = new Gson();
Map result = gson.fromJson(responseString, Map.class);
String access_token = "";
if (StringUtils.equals("00000", result.get("code").toString())) {
Map<String, Object> tokenInfo = (Map<String, Object>) result.get("data");
access_token = (String) tokenInfo.get("access_token");
}
Logger.error("SyncBipBillRuleForDelete-getAccessToken = " + access_token);
return access_token;
}
private String doGet(String requestUrl, Map<String, String> paramMap) throws IOException {
StringBuilder param = new StringBuilder("?");
if (paramMap != null) {
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
param.append(entry.getKey());
param.append("=");
param.append(entry.getValue());
param.append("&");
}
param.deleteCharAt(param.length() - 1);
}
String url = requestUrl + param;
URL u = new URL(url);
try {
if ("https".equalsIgnoreCase(u.getProtocol())) {// 判定网址是否信任不信任则调用忽略信任工具类SslUtil
IgnoreSslUtil.ignoreSsl();
}
HttpsURLConnection connection = (HttpsURLConnection) u.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
StringBuilder response = new StringBuilder();
int responsecode = connection.getResponseCode();
if (responsecode == HttpsURLConnection.HTTP_OK) {
InputStream inputstream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputstream));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
}
connection.disconnect();
return response.toString();
} catch (Exception e) {
Logger.error("SyncBipBillRuleForDelete-doGet:" + e.getMessage(), e);
}
return null;
}
private String doPost(String requestUrl, JSONObject json) throws IOException {
URL u = new URL(requestUrl);
try {
if ("https".equalsIgnoreCase(u.getProtocol())) {// 判定网址是否信任不信任则调用忽略信任工具类SslUtil
IgnoreSslUtil.ignoreSsl();
}
HttpsURLConnection connection = (HttpsURLConnection) u.openConnection();
// 设置请求方法
connection.setRequestMethod("POST");
// 设置请求属性
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
// 发送POST请求必须设置如下两行
connection.setDoOutput(true);
connection.setDoInput(true);
byte[] outputInBytes = json.toJSONString().getBytes(StandardCharsets.UTF_8);
// 写入数据到请求体
OutputStream os = connection.getOutputStream();
os.write(outputInBytes);
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应
String response = "";
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
br.readLine();
// System.out.println("Response: " + response);
}
// 关闭连接
connection.disconnect();
return response;
} catch (Exception e) {
Logger.error("SyncBipBillRuleForDelete-doPost:" + e.getMessage(), e);
}
return null;
}
}

View File

@ -0,0 +1,598 @@
package nc.bs.uapbd.bip.workplugin;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.yonyou.cloud.utils.StringUtils;
import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.pub.pa.PreAlertObject;
import nc.bs.pub.taskcenter.BgWorkingContext;
import nc.bs.pub.taskcenter.IBackgroundWorkPlugin;
import nc.bs.trade.business.HYSuperDMO;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.util.mmf.framework.base.MMValueCheck;
import nc.vo.bd.defdoc.DefdocVO;
import nc.vo.pub.BusinessException;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
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.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.GZIPInputStream;
/**
* 定时任务-回写bip合同销售订单字段
* 2005适配2312
*
* @author mzr
* @date 2025/3/26
*/
public class ErpSaleOrderToBIPBackgroupWorkPlugin implements IBackgroundWorkPlugin {
private HYSuperDMO superDMO = null;
private String baseUrl = "https://www.tkkfbip.com";
public HYSuperDMO getSuperDMO() {
if (superDMO == null) {
superDMO = new HYSuperDMO();
}
return superDMO;
}
/**
* 检查bip参数是否完整
*
* @return
*/
private Map<String, String> checkBipParam() {
Map<String, String> map = new HashMap<String, String>();
String strWhere = " pk_defdoclist in (select pk_defdoclist from bd_defdoclist where code='BIP-sq' and dr=0 ) and dr=0";
try {
DefdocVO[] defdocVOs = (DefdocVO[]) getSuperDMO().queryByWhereClause(DefdocVO.class, strWhere);
if (defdocVOs != null && defdocVOs.length > 0) {
for (DefdocVO defdocVO : defdocVOs) {
map.put(defdocVO.getCode().trim(), defdocVO.getName());
}
}
} catch (DAOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}
@Override
public PreAlertObject executeTask(BgWorkingContext arg0) throws BusinessException {
// TODO Auto-generated method stub
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateTime = dateFormat.format(date);
Map<String, String> bipParamMap = checkBipParam();
if (bipParamMap.isEmpty()) {
return null;
}
baseUrl = bipParamMap.get("baseUrl");
Map<String, Object> userMap = arg0.getKeyMap();
String usercustcode = "";
if (!userMap.isEmpty()) {
if (userMap.get("code") != null) {
usercustcode = userMap.get("code").toString();
}
}
String invoiceReceiveUrl = bipParamMap.get("contractSaleOrder");// 开票申请单回传
if (StringUtils.isEmpty(invoiceReceiveUrl)) {
return null;
}
Gson gson = new Gson();
// 获取未推送合同销售订单更新的销售发票信息
String sql = " select so_saleinvoice_b.cfirstbid,csaleinvoicebid from so_saleinvoice,so_saleinvoice_b where so_saleinvoice.csaleinvoiceid=so_saleinvoice_b.csaleinvoiceid and so_saleinvoice.fstatusflag=2 and nvl(so_saleinvoice_b.vbdef10,'N') in ('~','N') and nvl(so_saleinvoice.vdef13,'~') not in ('~') ";
List<Map<String, String>> l_pk = (List<Map<String, String>>) new BaseDAO().executeQuery(sql.toString(), new MapListProcessor());
if (l_pk.isEmpty()) {
return null;
}
for (Map<String, String> map : l_pk) {
StringBuffer sb = new StringBuffer();
sb.append(" select so_saleinvoice_b.csaleinvoicebid,so_saleorder.vdef9,so_saleorder_b.vbdef11,so_saleorder_exe.ntotalarmny as totalaccrued ,so_saleorder_exe.ntotalinvoicenum as billqty, NVL(so_saleorder_exe.ntotaloutnum, 0) as totaloutqty ");
sb.append(" from so_saleorder_exe,so_saleinvoice_b,so_saleinvoice,so_saleorder_b,so_saleorder ");
sb.append(" where so_saleorder_exe.csaleorderbid=so_saleinvoice_b.csrcbid ");
sb.append(" and so_saleinvoice.csaleinvoiceid=so_saleinvoice_b.csaleinvoiceid and so_saleinvoice.fstatusflag=2 ");
sb.append(" and so_saleorder_exe.csaleorderbid=so_saleorder_b.csaleorderbid ");
sb.append(" and so_saleorder.csaleorderid=so_saleorder_b.csaleorderid ");
sb.append(" and so_saleorder_exe.dr=0 and so_saleorder.dr=0 and so_saleorder_b.dr=0 ");
sb.append(" and nvl(so_saleorder.vdef9,'~') not in ('~') ");
sb.append(" and so_saleorder_exe.csaleorderbid='").append(map.get("cfirstbid")).append("'");
List<Map<String, String>> ll_saleorder = (List<Map<String, String>>) new BaseDAO().executeQuery(sb.toString(), new MapListProcessor());
if (ll_saleorder.isEmpty()) {
continue;
}
try {
String accessToken = getAccessToken(baseUrl, bipParamMap);
Map<String, String> tokenParam = new HashMap<>();
tokenParam.put("access_token", accessToken);
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
String custUpdateUrl = baseUrl + invoiceReceiveUrl;
if (accessToken != "") {
JSONObject js_apct_detail = new JSONObject();
JSONObject js_apct = new JSONObject();
String hid = ll_saleorder.get(0).get("vdef9");// BIP合同销售订单更新 主表id
List<Map<String, Object>> l_map_f = new ArrayList<Map<String, Object>>();
for (Map<String, String> custpkmap : ll_saleorder) {
Map<String, Object> b_map = new HashMap<String, Object>();
b_map.put("id", custpkmap.get("vbdef11"));// BIP合同销售订单更新 子表id
b_map.put("billQty", custpkmap.get("billqty"));// 累计开票主数量
b_map.put("totalAccrued", custpkmap.get("totalaccrued"));// 累计确认应收金额
b_map.put("totalOutQty", custpkmap.get("totaloutqty"));// 累计出库主数量
l_map_f.add(b_map);
js_apct.put("contractOrdersList", l_map_f);
js_apct.put("id", hid);
js_apct_detail.put("HTXSDD", js_apct);
String resultString = doSendHttp(custUpdateUrl, "POST", tokenParam, "", headers, js_apct_detail.toJSONString());
Map updateMap = gson.fromJson(resultString, Map.class);
String updateSql = "";
if (StringUtils.equals("200", updateMap.get("code").toString())) {// 保存更新成功后需要更新日志表
updateSql = "update so_saleinvoice_b set vbdef10='Y' where csaleinvoiceid='" + map.get("csaleinvoicebid") + "'";
} else {
updateSql = "update so_saleinvoice_b set vbdef10='N' where csaleinvoiceid='" + map.get("csaleinvoicebid") + "'";
}
getSuperDMO().executeUpdateSQL(updateSql);
}
}
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// 获取BIP的token
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
/**
* 查询bip 中开户行及银行类型id
*
* @param map
* @param bipUrl
* @return
*/
private static Map<String, String> getBIPBankID(HashMap<String, String> map, String bipUrl, String accessToken, String bankdocname) {
Gson gson = new Gson();
Map<String, String> tokenParam = new HashMap<>();
tokenParam.put("access_token", accessToken);
String jsonData = JSON.toJSONString(map);
String resultString = doSendHttp(bipUrl, "POST", tokenParam, "", new HashMap<>(), jsonData);
// Map custDetailresult = gson.fromJson(resultString, Map.class);
JSONObject custDetailresult = JSON.parseObject(resultString);
if (StringUtils.equals("200", custDetailresult.get("code").toString())) {// 数据存在
Map<String, Object> dataInfo = (Map<String, Object>) custDetailresult.get("data");
if (!MMValueCheck.isEmpty(dataInfo.get("recordList"))) {
List<Map<String, String>> l_record = (List<Map<String, String>>) dataInfo.get("recordList");
return l_record.get(0);
} else {
map.remove("linenumber");
map.put("name", bankdocname);
jsonData = JSON.toJSONString(map);
resultString = doSendHttp(bipUrl, "POST", tokenParam, "", new HashMap<>(), jsonData);
// custDetailresult = gson.fromJson(resultString, Map.class);
custDetailresult = JSON.parseObject(resultString);
if (StringUtils.equals("200", custDetailresult.get("code").toString())) {// 数据存在
dataInfo = (Map<String, Object>) custDetailresult.get("data");
if (!MMValueCheck.isEmpty(dataInfo.get("recordList"))) {
List<Map<String, String>> l_record = (List<Map<String, String>>) dataInfo.get("recordList");
return l_record.get(0);
}
}
}
}
return null;
}
public static String doSendHttp(String baseUrl, String method, Map<String, String> paramMap, String mediaType, Map<String, String> headers, String json) {
HttpURLConnection urlConnection = null;
InputStream in = null;
OutputStream out = null;
BufferedReader bufferedReader = null;
String result = null;
try {
StringBuffer sb = new StringBuffer();
sb.append(baseUrl);
if (paramMap != null) {
sb.append("?");
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key + "=" + value).append("&");
baseUrl = sb.toString().substring(0, sb.toString().length() - 1);
}
}
// log.error("uRL:" + baseUrl);
// // 打印请求URL和方法
// log.error("Request URL: " + baseUrl);
// log.error("Request Method: " + method);
URL urlobj = new URL(baseUrl);
if ("https".equalsIgnoreCase(urlobj.getProtocol())) {// 判定网址是否信任不信任则调用忽略信任工具类SslUtil
IgnoreSslUtil.ignoreSsl();
}
urlConnection = (HttpURLConnection) urlobj.openConnection();
urlConnection.setConnectTimeout(50000);
urlConnection.setRequestMethod(method);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
// 如果设置了自定义头则打印它们
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
urlConnection.addRequestProperty(entry.getKey(), entry.getValue());
// log.error("Request Header: " + entry.getKey() + ": " + entry.getValue());
}
}
if (json != null && json.length() > 0) {
// log.error("Request Body: " + json);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
out = urlConnection.getOutputStream();
out.write(json.getBytes("utf-8"));
out.flush();
}
int resCode = urlConnection.getResponseCode();
String ecod = urlConnection.getContentEncoding();
if (resCode == HttpURLConnection.HTTP_OK || resCode == HttpURLConnection.HTTP_CREATED
|| resCode == HttpURLConnection.HTTP_ACCEPTED) {
if (StringUtils.isNotEmpty(ecod) && ecod.equals("gzip")) {
in = new GZIPInputStream(urlConnection.getInputStream());
} else {
in = urlConnection.getInputStream();
}
} else {
in = urlConnection.getErrorStream();
}
bufferedReader = new BufferedReader(new InputStreamReader(in, "utf-8"));
StringBuffer temp = new StringBuffer();
String line = bufferedReader.readLine();
while (line != null) {
temp.append(line).append("\r\n");
line = bufferedReader.readLine();
}
if (ecod == null || ecod.equals("gzip")) {
ecod = Charset.forName("utf-8").name();
}
result = new String(temp.toString().getBytes("utf-8"), ecod);
} catch (Exception e) {
JSONObject js = new JSONObject();
js.put("", -1);
js.put("message", "调用外系统接口失败:" + e.getMessage());
result = js.toString();
e.printStackTrace();
} finally {
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
urlConnection.disconnect();
}
return result;
}
// private String createCustBankMap(Map<String,String> map,String access_token) {
// Gson gson = new Gson();
// //获取BIP中的客户详情
// String custcode=map.get("custcode");
// String custurl=baseUrl+"/yonbip/digitalModel/merchant/detail?access_token="+access_token;
// HashMap<String, String> custMap = new HashMap<String, String>();
// custMap.put("code", custcode);
// try {
// String custdetailString=doGet(custurl,custMap);
//
// Map custDetailresult = gson.fromJson(custdetailString, Map.class);
// if (StringUtils.equals("200", custDetailresult.get("code").toString())) {//客户存在
//
// Map<String, Object> dataInfo = (Map<String, Object>) custDetailresult.get("data");
//
// if (!MMValueCheck.isEmpty(dataInfo.get("merchantAgentFinancialInfos"))){//客户中已经存在银行账户
//
// }else {
//
// }
//
// }
//
//
// //开户行
// String bankdoccode=map.get("bankdoccode");
// HashMap<String, Object> paramap = new HashMap<String, Object>();
// paramap.put("pageIndex", 0);
// paramap.put("pageSize", 10);
// paramap.put("linenumber", bankdoccode);
// String url=baseUrl+"/yonbip/digitalModel/bankdot/list?access_token="+access_token;
//
// String responseString=doPost(url,paramap);
//
// Map result = gson.fromJson(responseString, Map.class);
//
// } catch (IOException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
//
// }
private String getAccessToken(String baseUrl, Map<String, String> bipParamMap) throws NoSuchAlgorithmException, InvalidKeyException, IOException {
String tokenUrl = baseUrl + "/iuap-api-auth/open-auth/selfAppAuth/getAccessToken";
// String appKey = "f10c4bf17b1d4e1fb08eb82bf8540eab";
String appKey = bipParamMap.get("appKey");
// String appSecret = "71dc2a58ca378c1a1143231a62e73e75a60e9236";
String appSecret = bipParamMap.get("appSecret");
String accessToken = "";
Map<String, String> params = new HashMap<>();
params.put("appKey", appKey);
String timestamp = String.valueOf(System.currentTimeMillis());
params.put("timestamp", timestamp);
// 计算签名
Map<String, String> treeMap;
if (params instanceof TreeMap) {
treeMap = params;
} else {
treeMap = new TreeMap<>(params);
}
StringBuilder stringBuilder = new StringBuilder();
for (Map.Entry<String, String> entry : treeMap.entrySet()) {
stringBuilder.append(entry.getKey()).append(entry.getValue());
}
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(appSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] signData = mac.doFinal(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
String base64String = Base64.getEncoder().encodeToString(signData);
String signature = URLEncoder.encode(base64String, "UTF-8");
params.put("signature", signature);
String responseString = doGet(tokenUrl, params);
Gson gson = new Gson();
Map result = gson.fromJson(responseString, Map.class);
if (StringUtils.equals("00000", result.get("code").toString())) {
Map<String, Object> tokenInfo = (Map<String, Object>) result.get("data");
accessToken = (String) tokenInfo.get("access_token");
}
return accessToken;
}
private String doPost(String requestUrl, JSONObject jsonObject) throws IOException {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(500);
cm.setDefaultMaxPerRoute(50);
RequestConfig globalConfig = RequestConfig.custom().setConnectionRequestTimeout(5000) // 连接池获取连接超时
.setConnectTimeout(5000) // 连接建立超时
.setSocketTimeout(20000) // 等待响应超时
.setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm)
.setDefaultRequestConfig(globalConfig).build();
HttpPost post = new HttpPost(requestUrl);
post.setHeader("Content-Type", "application/json;charset=UTF-8");
post.setEntity(new StringEntity(JSONObject.toJSONString(jsonObject), "utf-8"));
String responseString = httpClient.execute(post, response -> EntityUtils.toString(response.getEntity()));
return responseString;
}
private String doPost(String requestUrl, Map<String, Object> param) throws IOException {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(500);
cm.setDefaultMaxPerRoute(50);
RequestConfig globalConfig = RequestConfig.custom().setConnectionRequestTimeout(5000) // 连接池获取连接超时
.setConnectTimeout(5000) // 连接建立超时
.setSocketTimeout(20000) // 等待响应超时
.setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm)
.setDefaultRequestConfig(globalConfig).build();
HttpPost post = new HttpPost(requestUrl);
post.setHeader("Content-Type", "application/json;charset=UTF-8");
post.setEntity(new StringEntity(JSONObject.toJSONString(param), "utf-8"));
String responseString = httpClient.execute(post, response -> EntityUtils.toString(response.getEntity()));
return responseString;
}
private static String doGet(String path, Map<String, String> params) throws IOException {
HttpURLConnection conn = null;
InputStream is = null;
BufferedReader br = null;
StringBuilder result = new StringBuilder();
try {
if (params != null) {
String paramStr = "";
for (String key : params.keySet()) {
if (!paramStr.isEmpty()) {
paramStr += '&';
}
paramStr += key + '=' + params.get(key);
}
if (path.indexOf('?') > 0) {
path += '&' + paramStr;
} else {
path += '?' + paramStr;
}
}
// 创建远程url连接对象
URL url = new URL(path);
if ("https".equalsIgnoreCase(url.getProtocol())) {// 判定网址是否信任不信任则调用忽略信任工具类SslUtil
IgnoreSslUtil.ignoreSsl();
}
// 通过远程url连接对象打开一个连接强转成HTTPURLConnection类
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// 设置连接超时时间和读取超时时间
conn.setConnectTimeout(120000);
conn.setReadTimeout(120000);
conn.setRequestProperty("Accept", "application/json");
// 发送请求
conn.connect();
// 通过conn取得输入流并使用Reader读取
if (200 == conn.getResponseCode()) {
is = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line;
while ((line = br.readLine()) != null) {
result.append(line);
System.out.println(line);
}
} else {
System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// finally {
// try {
// if (br != null) {
// br.close();
// }
// if (is != null) {
// is.close();
// }
// } catch (IOException ioe) {
// ioe.printStackTrace();
// }
// conn.disconnect();
// }
return result.toString();
}
// private String doGet(String requestUrl, Map<String, String> paramMap) throws IOException {
// PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
// cm.setMaxTotal(500);
// cm.setDefaultMaxPerRoute(50);
//
// RequestConfig globalConfig = RequestConfig.custom().setConnectionRequestTimeout(5000) // 连接池获取连接超时
// .setConnectTimeout(5000) // 连接建立超时
// .setSocketTimeout(20000) // 等待响应超时
// .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
//
// CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm)
// .setDefaultRequestConfig(globalConfig).build();
// StringBuilder param = new StringBuilder("?");
// if (paramMap != null) {
// for (Map.Entry<String, String> entry : paramMap.entrySet()) {
// param.append(entry.getKey());
// param.append("=");
// param.append(entry.getValue());
// param.append("&");
// }
// param.deleteCharAt(param.length() - 1);
// }
// String url = requestUrl + param;
// HttpGet get = new HttpGet(url);
// String responseString = httpClient.execute(get, response -> EntityUtils.toString(response.getEntity()));
// get.releaseConnection();
// return responseString;
// }
}

View File

@ -0,0 +1,60 @@
package nc.bs.uapbd.bip.workplugin;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class IgnoreSslUtil {
private static void trustAllHttpsCertificates() throws Exception {
TrustManager[] trustAllCerts = new TrustManager[1];
TrustManager tm = new miTM();
trustAllCerts[0] = tm;
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
static class miTM implements TrustManager,X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(X509Certificate[] certs, String authType)
throws CertificateException {
return;
}
public void checkClientTrusted(X509Certificate[] certs, String authType)
throws CertificateException {
return;
}
}
/**
* 忽略HTTPS请求的SSL证书必须在openConnection之前调用
* @throws Exception
*/
public static void ignoreSsl() throws Exception{
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
return true;
}
};
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
}

View File

@ -0,0 +1,60 @@
package nc.bs.uapbd.util;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class IgnoreSslUtil {
private static void trustAllHttpsCertificates() throws Exception {
TrustManager[] trustAllCerts = new TrustManager[1];
TrustManager tm = new miTM();
trustAllCerts[0] = tm;
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
static class miTM implements TrustManager,X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(X509Certificate[] certs, String authType)
throws CertificateException {
return;
}
public void checkClientTrusted(X509Certificate[] certs, String authType)
throws CertificateException {
return;
}
}
/**
* 忽略HTTPS请求的SSL证书必须在openConnection之前调用
* @throws Exception
*/
public static void ignoreSsl() throws Exception{
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
return true;
}
};
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
}