Search in sources :

Example 6 with EvidenceCertificate

use of com.itrus.portal.db.EvidenceCertificate in project portal by ixinportal.

the class EvidenceSaveTask method saveBody.

// private AtomicInteger counter = new AtomicInteger(0);
// private static final String CERT_VERIFY = "/cert/verify";
// 验证pdf文档签章
// private static final String PDF_VERIFY = "/pdf/verify";
// private Map<String, Object> result;
// private ApplicationInfo applicationInfo;
// private AppService appService;
// private EvidenceSaveService evidenceSaveService;
// private Date applyDate;
// private String evidenceSn;
// private String genSn;
// private String signedBase64;
// private String evidencePackage;
// private String hashAlg;
// private String hashvalue;
// private Date dateVp;
// private Date dateVc;
// private List<String> certs;
// private RealNameAuthentication realNameAuthentication;
// private RealNameAuthentication realNameAuthenticationTime;
// private RealNameAuthentication realNameAuthenticationOss;
// private Map<String, Object> mapCharging;
// private static EvidenceSaveTask evidenceSaveTask;
// public static EvidenceSaveTask getInstance() {
// if(evidenceSaveTask == null) {
// synchronized (EvidenceSaveTask.class) {
// evidenceSaveTask = new EvidenceSaveTask();
// }
// }
// return evidenceSaveTask;
// }
// public EvidenceSaveTask () {
// super();
// }
// private ScheduledTask scheduledTask = SpringContextHolder.getBean(ScheduledTask.class);
// public EvidenceSaveTask(Map<String, Object> result, ApplicationInfo applicationInfo, AppService appService,
// EvidenceSaveService evidenceSaveService,  Date applyDate, String evidenceSn, String genSn,
// String signedBase64, String evidencePackage, String hashAlg, String hashvalue, Date dateVp,
// Date dateVc, List<String> certs, RealNameAuthentication realNameAuthentication,
// RealNameAuthentication realNameAuthenticationTime, RealNameAuthentication realNameAuthenticationOss,
// Map<String, Object> mapCharging) {
// this.result = result;
// this.applicationInfo = applicationInfo;
// this.appService = appService;
// this.evidenceSaveService = evidenceSaveService;
// this.applyDate = applyDate;
// this.evidenceSn = evidenceSn;
// this.genSn = genSn;
// this.signedBase64 = signedBase64;
// this.evidencePackage = evidencePackage;
// this.hashAlg = hashAlg;
// this.hashvalue = hashvalue;
// this.dateVp = dateVp;
// this.dateVc = dateVc;
// this.certs = certs;
// this.realNameAuthentication = realNameAuthentication;
// this.realNameAuthenticationTime = realNameAuthenticationTime;
// this.realNameAuthenticationOss = realNameAuthenticationOss;
// this.mapCharging = mapCharging;
// }
/**
 * 删除证件包
 * @param fileName
 * @return
 * @throws Exception
 */
// public boolean deleteEvidence(String fileName) throws Exception{
// try {
// File file = new File(systemConfigService.getpdfurl(), fileName);
// if(file.exists()) {
// return file.delete();
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// return false;
// }
/**
 * 核验处理方法
 * @param result
 * 			返回值
 * @param applicationInfo
 * 			应用
 * @param evidenceSaveService
 * 			服务配置
 * @param evidenceSn
 * 			证据编号
 * @param signedBase64
 * 			签名值
 * @param evidencePackage
 * 			证据包
 * @return
 * @throws Exception
 */
public Map<String, Object> saveBody(Map<String, Object> result, ApplicationInfo applicationInfo, AppService appService, EvidenceSaveService evidenceSaveService, Date applyDate, String evidenceSn, String genSn, String signedBase64, String evidencePackage, String hashAlg, String hashvalue, Date dateVp, Date dateVc, List<String> certs, RealNameAuthentication realNameAuthentication, RealNameAuthentication realNameAuthenticationTime, RealNameAuthentication realNameAuthenticationOss, Map<String, Object> mapCharging) throws Exception {
    List<Object> objs = new ArrayList<Object>();
    String info = null;
    // 证据服务记录
    EvidenceBasicInformation basicInformation = null;
    // 本次证据包大小
    int fileSize = evidencePackage.getBytes().length;
    // 定义一个证据的提交次数
    int count = 0;
    try {
        // 定义时间戳固定时间
        // Date genTime = null;
        String failureReason = null;
        JSONObject jsonEvidenceContent = JSONObject.parseObject(evidencePackage);
        // 定义证书固定服务配置
        EvidenceServiceConfiguration serviceConfiguration = null;
        // 定义证书固定服务配置
        serviceConfiguration = CacheCustomer.getEVIDENCE_SERVICE_CONFIG();
        if (serviceConfiguration == null) {
            // 得到证书固定服务配置
            List<EvidenceServiceConfiguration> serviceconfig = sqlSession.selectList("com.itrus.portal.db.EvidenceServiceConfigurationMapper.selectByExample");
            if (!serviceconfig.isEmpty()) {
                serviceConfiguration = serviceconfig.get(0);
                CacheCustomer.setEVIDENCE_SERVICE_CONFIG(serviceConfiguration);
            } else {
                result.put("status", -22);
                result.put("message", "缺少服务配置");
                return result;
            }
        }
        // 验签信息入库
        EvidenceClientSignature clientSignature = new EvidenceClientSignature();
        clientSignature.setHashAlgorithm(hashAlg);
        clientSignature.setHashvalue(hashvalue);
        clientSignature.setName("0");
        // ---- 关联证书
        clientSignature.setCertId(Long.parseLong(applicationInfo.getCertBase64()));
        clientSignature.setSignatureType("2");
        clientSignature.setIdentiType("1");
        clientSignature.setSignaturevalue(signedBase64);
        clientSignature.setCreateTime(dateVp);
        // clientSignature.setCreateTimeMs(applyDate.getTime());
        if (StringUtils.isNotEmpty(evidenceSn))
            clientSignature.setEvidenceSn(evidenceSn);
        else
            clientSignature.setEvidenceSn(genSn);
        // queueThread.putObjectQueue(clientSignature);
        objs.add(clientSignature);
        clientSignature = null;
        // 密钥别名定义
        String alias = null;
        // 判断是否需要签名或时间戳
        if (evidenceSaveService.getFixationWay() != null && evidenceSaveService.getFixationWay() != 1) {
            // 判断是否需要签名
            if (evidenceSaveService.getFixationWay() == 2 || evidenceSaveService.getFixationWay() == 4) {
                // 定义签名参数
                Map<String, Object> param = new HashMap<String, Object>();
                String url = null;
                // 判断签名类型配置是否为空
                if (StringUtils.isNotBlank(serviceConfiguration.getSignatureType())) {
                    // 得到配置证书
                    EvidenceCertificate evidenceCertificate = null;
                    evidenceCertificate = CacheCustomer.getEVIDENCE_CERTIFICATE_MAP().get((long) serviceConfiguration.getSignatureCertificate());
                    if (evidenceCertificate == null) {
                        evidenceCertificate = certificateService.selectById((long) serviceConfiguration.getSignatureCertificate());
                    }
                    // 得到服务配置的签名证书的密钥别名
                    alias = CacheCustomer.getMAP_COMFIG().get((long) serviceConfiguration.getSignatureCertificate());
                    if (StringUtils.isEmpty(alias)) {
                        alias = secretKeyService.getAliasByCertId((long) serviceConfiguration.getSignatureCertificate());
                    }
                    // 配置签名url 和 参数   1.裸签名  2.p7分离式签名  3.p7非分离式签名  (本期只做2)
                    switch(Integer.parseInt(serviceConfiguration.getSignatureType())) {
                        case 1:
                            param.put("alias", alias);
                            param.put("hashAlg", serviceConfiguration.getArithmetic());
                            param.put("contentType", "CT_HASH");
                            url = realNameAuthentication.getRealNameddress() + SIGNATURE_SIGN;
                            break;
                        case 2:
                            param.put("alias", alias);
                            param.put("hashAlg", serviceConfiguration.getArithmetic());
                            param.put("detached", true);
                            param.put("contentType", "CT_HASH");
                            param.put("content", HMACSHA1.getDigest(serviceConfiguration.getArithmetic(), evidencePackage));
                            url = realNameAuthentication.getRealNameddress() + P7_SIGN;
                            break;
                        case 3:
                            param.put("alias", alias);
                            param.put("hashAlg", serviceConfiguration.getArithmetic());
                            param.put("detached", false);
                            param.put("contentType", "CT_HASH");
                            param.put("content", HMACSHA1.getDigest(serviceConfiguration.getArithmetic(), evidencePackage));
                            url = realNameAuthentication.getRealNameddress() + P7_SIGN;
                            break;
                    }
                    // 异步处理p7签名
                    // HttpAsyncClientUtil.getInstance().execute(
                    // url,
                    // AuthService.getHeader(),
                    // param,
                    // new EvidenceSignTask(
                    // url,
                    // param,
                    // evidenceSn!=null?evidenceSn:genSn,
                    // Long.parseLong(evidenceCertificate.getCert())));
                    String strP7 = null;
                    try {
                        // strP7 = clientService.postForm(url, AuthService.getHeader(), param);
                        strP7 = OkHttpClientManagerSign.post(url, AuthService.getHeader().get("Authorization").toString(), param);
                    } catch (Exception e) {
                        e.printStackTrace();
                        LogUtil.evidencelog(sqlSession, (evidenceSn != null ? evidenceSn : genSn).toString(), "存证接口_天威签名", "天威签名失败,证据编号:" + (evidenceSn != null ? evidenceSn : genSn).toString() + ", 请求参数:" + param.toString() + ", 请求地址:" + url + ", 返回结果:" + strP7 + ", 失败原因:" + e.toString());
                        // TODO: handle exception
                        result.put("status", 0);
                        result.put("message", "天威签名失败");
                        return result;
                    }
                    // log.error("strP7 : " + strP7);
                    JSONObject jsonRepP7Sign = JSONObject.parseObject(strP7);
                    if (jsonRepP7Sign.getIntValue("code") != 0) {
                        // 天威签名失败
                        LogUtil.evidencelog(sqlSession, (evidenceSn != null ? evidenceSn : genSn).toString(), "存证接口_天威签名", "天威签名失败,证据编号:" + (evidenceSn != null ? evidenceSn : genSn).toString() + ", 请求参数:" + param.toString() + ", 请求地址:" + url + ", 返回结果:" + strP7 + ", 失败原因:" + jsonRepP7Sign.getString("message"));
                        result.put("status", 0);
                        result.put("message", "天威签名失败");
                        return result;
                    } else {
                        // 天威签名服务记录入库
                        EvidenceClientSignature signature = new EvidenceClientSignature();
                        signature.setHashAlgorithm(param.get("hashAlg").toString());
                        signature.setName("1");
                        signature.setEvidenceSn(evidenceSn != null ? evidenceSn : genSn);
                        signature.setSignatureType("2");
                        signature.setCertId(Long.parseLong(evidenceCertificate.getCert()));
                        signature.setHashvalue(param.get("content").toString());
                        signature.setSignaturevalue(jsonRepP7Sign.getString("signedData"));
                        signature.setCreateTime(new Date());
                        // signature.setCreateTimeMs(applyDate.getTime());
                        objs.add(signature);
                    }
                    evidenceCertificate = null;
                }
            }
            // 判断是否需要签名时间戳
            if (evidenceSaveService.getFixationWay() == 3 || evidenceSaveService.getFixationWay() == 4) {
                // 对证据包HASH
                String plainHash = HMACSHA1.getDigest(serviceConfiguration.getArithmetic(), evidencePackage);
                // 异步处理时间戳   ---  本期是实现新版本接口
                Map<String, Object> retTime = EvidenceSaveServiceApi.genTimeStamp(realNameAuthenticationTime, plainHash, serviceConfiguration.getArithmetic(), evidenceSn != null ? evidenceSn : genSn, null);
                if (!(boolean) retTime.get("retStatus") && retTime.get("obj") != null) {
                    result.put("status", 0);
                    result.put("message", "天威时间戳签名失败");
                    return result;
                }
                objs.add(retTime.get("obj"));
            }
        }
        alias = null;
        Map<String, Object> retSaveMap = new HashMap<String, Object>();
        // 判断证据编号是否为空   true -> 证据编码为空 代表第一次存证   ,false ->证据编码不为空 代表不是第一次存证
        if (StringUtils.isEmpty(evidenceSn)) {
            basicInformation = new EvidenceBasicInformation();
            basicInformation.setReceiptStatus(0);
            basicInformation.setStatus(0);
            basicInformation.setIsCallback(0);
            basicInformation.setCreateTime(new Date());
            // basicInformation.setCreateTimeMs(applyDate.getTime());
            basicInformation.setEndTime(EvidenceSaveServiceApi.convertDate(evidenceSaveService.getSaveTime()));
            basicInformation.setEvidenceSize(fileSize);
            basicInformation.setEvidenceSn(genSn);
            basicInformation.setAppService(appService.getId());
            basicInformation.setEvidenceStatus(1);
            basicInformation.setApplicationInfo(applicationInfo.getId());
            basicInformation.setOutAppService(evidenceSaveService.getAppServiceName());
            basicInformation.setSaveServiceNmae(appService.getAppServiceName());
            basicInformation.setServicePlatformName(applicationInfo.getName());
            basicInformation.setServiceClientName(applicationInfo.getServiceClientName());
            basicInformation.setServiceClientId(applicationInfo.getServiceClientId());
            if (StringUtils.isNotEmpty(failureReason)) {
                basicInformation.setFailureReason(failureReason);
                basicInformation.setEvidenceStatus(0);
                result.put("status", 0);
            }
            // 对要素 (接收 核验 必填) 操作进行处理
            retSaveMap = saveFactor(retSaveMap, evidenceSaveService, genSn, jsonEvidenceContent, basicInformation, realNameAuthentication, realNameAuthenticationOss, serviceConfiguration, true);
        } else {
            EvidenceBasicInformationExample basicInformationExample = new EvidenceBasicInformationExample();
            EvidenceBasicInformationExample.Criteria beCriteria = basicInformationExample.createCriteria();
            beCriteria.andEvidenceSnEqualTo(evidenceSn);
            List<EvidenceBasicInformation> basicInformationList = sqlSession.selectList("com.itrus.portal.db.EvidenceBasicInformationMapper.selectByExample", basicInformationExample);
            if (basicInformationList.size() == 0 || basicInformationList.isEmpty()) {
                result.put("status", 0);
                result.put("message", "未找到对应证据编号信息");
                return result;
            }
            basicInformation = basicInformationList.get(0);
            if (basicInformation.getEvidenceStatus() != null && basicInformation.getEvidenceStatus() == 0) {
                result.put("status", 0);
                result.put("message", "本次证据补交失败。对应证据编号已存在核验失败信息,原因:" + basicInformation.getFailureReason());
                return result;
            }
            // 得到提交次数
            EvidenceEnclosureExample enclosureExample = new EvidenceEnclosureExample();
            EvidenceEnclosureExample.Criteria eec = enclosureExample.createCriteria();
            eec.andBasicInformationEqualTo(basicInformation.getId());
            eec.andPdfTypeEqualTo("1");
            List<EvidenceEnclosure> enclosures = sqlSession.selectList("com.itrus.portal.db.EvidenceEnclosureMapper.selectByExample", enclosureExample);
            if (!enclosures.isEmpty()) {
                count = enclosures.size();
            }
            basicInformation.setEvidenceSize(basicInformation.getEvidenceSize() + fileSize);
            basicInformation.setAppService(appService.getId());
            // 对要素 (接收 核验) 操作进行处理
            retSaveMap = saveFactor(retSaveMap, evidenceSaveService, evidenceSn, jsonEvidenceContent, basicInformation, realNameAuthentication, realNameAuthenticationOss, serviceConfiguration, false);
        }
        String saveFactor = null;
        if (retSaveMap.get("status") != null) {
            result.put("status", retSaveMap.get("status"));
            result.put("message", retSaveMap.get("message"));
            return result;
        } else {
            List<Object> lists = (List<Object>) retSaveMap.get("objs");
            for (Object obj : lists) {
                objs.add(obj);
            }
        }
        basicInformation = (EvidenceBasicInformation) retSaveMap.get("basicInformation");
        if (basicInformation.getEvidenceStatus() != null && basicInformation.getEvidenceStatus() == 0) {
            result.put("status", 0);
            result.put("message", basicInformation.getEvidenceStatus());
            return result;
        }
        // 得到加密证书别名
        alias = CacheCustomer.getMAP_COMFIG().get((long) serviceConfiguration.getEncryptionCertificate());
        if (StringUtils.isEmpty(alias)) {
            alias = secretKeyService.getAliasByCertId((long) serviceConfiguration.getEncryptionCertificate());
        }
        // 内部加密存储证据包
        String urlSave = realNameAuthentication.getRealNameddress() + "/storage/save";
        Map<String, Object> mapSave = new HashMap<String, Object>();
        mapSave.put("type", "ST_E");
        mapSave.put("bucketName", realNameAuthenticationOss.getKeyCode());
        mapSave.put("objectName", applicationInfo.getServiceClientId() + "/" + (StringUtils.isEmpty(evidenceSn) ? genSn : evidenceSn) + (count + 1));
        mapSave.put("contentType", "CT_BASE64_DATA");
        mapSave.put("content", Base64.encode(evidencePackage.getBytes("utf-8")));
        mapSave.put("alias", alias);
        mapSave.put("digestZValue", false);
        mapSave.put("encAlg", serviceConfiguration.getEncryptionAlgorithm());
        if (result.get("saveFactor") != null) {
            saveFactor = retSaveMap.get("saveFactor").toString();
        }
        // 异步处理存储
        // HttpAsyncClientUtil.getInstance().execute(
        // urlSave,
        // AuthService.getHeader(),
        // mapSave,
        // new EvidenceSavePackageTask(
        // urlSave,
        // mapSave,
        // null,
        // evidenceSn!=null?evidenceSn:genSn,
        // Integer.toString(fileSize),
        // genTime,
        // applyDate,
        // Integer.toString(evidenceSaveService.getSaveTime()),
        // saveFactor));
        // String retSave = clientService.postForm(urlSave, AuthService.getHeader(), mapSave);
        String retSave = null;
        try {
            retSave = OkHttpClientManagerSave.post(urlSave, AuthService.getHeader().get("Authorization").toString(), mapSave);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LogUtil.evidencelog(sqlSession, (evidenceSn != null ? evidenceSn : genSn).toString(), "存证接口_存储数据包", "存储数据包失败,证据编号:" + (evidenceSn != null ? evidenceSn : genSn).toString() + ", 请求参数:" + mapSave.toString() + ", 请求地址:" + urlSave + ",返回结果" + retSave + ", 失败原因:" + e.toString());
            result.put("status", 0);
            result.put("message", "证据存储失败");
            return result;
        }
        JSONObject jsonSave = JSONObject.parseObject(retSave);
        if (jsonSave.getIntValue("code") != 0) {
            // 天威签名失败
            LogUtil.evidencelog(sqlSession, (evidenceSn != null ? evidenceSn : genSn).toString(), "存证接口_存储数据包", "存储数据包失败,证据编号:" + (evidenceSn != null ? evidenceSn : genSn).toString() + ", 请求参数:" + mapSave.toString() + ", 请求地址:" + urlSave + ",返回结果" + retSave + ", 失败原因:" + jsonSave);
            result.put("status", 0);
            result.put("message", "证据存储失败");
            return result;
        } else {
            EvidenceEnclosure enclosure = new EvidenceEnclosure();
            enclosure.setBuid(jsonSave.getString("buid"));
            enclosure.setEvidenceSn((evidenceSn != null ? evidenceSn : genSn).toString());
            enclosure.setFilesize(Integer.toString(fileSize));
            enclosure.setPdfType("1");
            enclosure.setApplicationTime(applyDate);
            enclosure.setCreateTime(new Date());
            // enclosure.setCreateTimeMs(applyDate.getTime());
            enclosure.setSaveTime(Integer.toString(evidenceSaveService.getSaveTime()));
            if (mapSave.get("type") != null)
                enclosure.setType(mapSave.get("type").toString());
            if (mapSave.get("contentType") != null)
                enclosure.setContentType(mapSave.get("contentType").toString());
            if (mapSave.get("bucketName") != null)
                enclosure.setBucketName(mapSave.get("bucketName").toString());
            if (mapSave.get("objectName") != null)
                enclosure.setObjectName(mapSave.get("objectName").toString());
            if (mapSave.get("alias") != null)
                enclosure.setAlias(mapSave.get("alias").toString());
            enclosure.setFixationTime(new Date());
            if (saveFactor != null) {
                enclosure.setSaveFactor(saveFactor);
            }
            // queueThread.putObjectQueue(enclosure);
            objs.add(enclosure);
        }
        // 判断是否为补交
        if (count > 0) {
            // 判断是否出过证据, true : 修改出证状态为部分出  ; 出证状态:0未出1待出2已出 3部分出 4出证失败
            if (basicInformation.getStatus() == 2) {
                basicInformation.setStatus(3);
            }
        }
        // }
        if ((int) result.get("status") == 1) {
        // 判断是否需要生成存在回执
        // if(evidenceSaveService.getAppServiceName() != null) {
        // // 生成存证回执报告 查询存证时
        // Map<String, Object> mapRet = reportTemplate.returnreceipt(basicInformation.getEvidenceSn(), applicationInfo);
        // if(mapRet.get("status") != null && (int)mapRet.get("status") == 0) {
        // basicInformation.setReceiptStatus(1);//存证回执状态1已出0未出
        // } else {
        // //    throw new Exception("生成存证回执报告失败," + mapRet.get("message"));
        // }
        // }
        // EvidenceSubmitDateExample dateExample = new EvidenceSubmitDateExample();
        // EvidenceSubmitDateExample.Criteria criteria = dateExample.createCriteria();
        // if(StringUtils.isNotBlank(evidenceSn))
        // criteria.andEvidenceSnEqualTo(evidenceSn);
        // else
        // criteria.andEvidenceSnEqualTo(genSn);
        // sqlSession.delete("com.itrus.portal.db.EvidenceClientTimeStampMapper.deleteByExample", dateExample);
        } else {
            basicInformation.setEvidenceStatus(0);
            if (StringUtils.isEmpty(basicInformation.getFailureReason())) {
                if (result.get("message") != null) {
                    basicInformation.setFailureReason(result.get("message").toString());
                }
            } else {
                if (result.get("message") != null) {
                    basicInformation.setFailureReason(basicInformation.getFailureReason() + "," + result.get("message").toString());
                }
            }
        }
        // queueThread.putObjectQueue(basicInformation);
        objs.add(basicInformation);
        queueThread.putListQueue(objs);
        // 记录计费流水
        if ((int) mapCharging.get("retCode") == 1) {
            // log.error("计费次数:" + counter.getAndIncrement());
            // log.error("【计费】");
            Map<String, Object> mapStoreCg = storeChargingService.storeCharging(appService.getServiceConfigName(), appService.getServiceConfigId(), applicationInfo, appService, null, "EvidenceBasicInformation", evidenceSaveService.getBaseSpace(), EvidenceSaveServiceApi.getSize(fileSize), StringUtils.isBlank(evidenceSn), (evidenceSn != null ? evidenceSn : genSn).toString());
            // + ",totalSize__ : " + EvidenceSaveServiceApi.getSize(fileSize));
            if ((int) mapStoreCg.get("retCode") != 1) {
                result.put("status", -4);
                result.put("message", "服务计费失败");
                return result;
            }
        }
    // sqlSession.update("com.itrus.portal.db.EvidenceBasicInformationMapper.updateByPrimaryKey", basicInformation);
    // sqlSession.flushStatements();
    // if((int)result.get("status") == 1) {
    // LogUtil.evidencelog(sqlSession, "存证接口", "存证基础信息保存成功,证据编号:" + basicInformation.getEvidenceSn());
    // } else {
    // LogUtil.evidencelog(sqlSession, "存证接口", "存证失败,详情:"+ basicInformation.getEvidenceSn()
    // + basicInformation.getFailureReason());
    // }
    } catch (Exception e) {
        e.printStackTrace();
        if (null == info) {
            info = "系统处理异常!";
        }
        // StackTraceElement stackTraceElement = e.getStackTrace()[e.getStackTrace().length-2];
        // info = stackTraceElement.getClassName() + stackTraceElement.getLineNumber() + e.toString();
        LogUtil.evidencelog(sqlSession, (evidenceSn != null ? evidenceSn : genSn).toString(), "存证接口", "存证失败,证据编号:" + (evidenceSn != null ? evidenceSn : genSn).toString() + ", 失败原因:" + e.toString());
        result.put("status", -5);
        result.put("message", "系统服务错误,请联系管理员");
        return result;
    } finally {
        result.remove("saveFactor");
        result.remove("basicInformation");
    }
    return result;
}
Also used : EvidenceBasicInformation(com.itrus.portal.db.EvidenceBasicInformation) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) EvidenceEnclosureExample(com.itrus.portal.db.EvidenceEnclosureExample) EvidenceEnclosure(com.itrus.portal.db.EvidenceEnclosure) Date(java.util.Date) EvidenceBasicInformationExample(com.itrus.portal.db.EvidenceBasicInformationExample) EvidenceServiceConfiguration(com.itrus.portal.db.EvidenceServiceConfiguration) JSONObject(com.alibaba.fastjson.JSONObject) EvidenceCertificate(com.itrus.portal.db.EvidenceCertificate) JSONObject(com.alibaba.fastjson.JSONObject) ArrayList(java.util.ArrayList) List(java.util.List) EvidenceClientSignature(com.itrus.portal.db.EvidenceClientSignature)

Example 7 with EvidenceCertificate

use of com.itrus.portal.db.EvidenceCertificate in project portal by ixinportal.

the class CertificateController method update.

/**
 * 修改处理
 *
 * @param configuration
 * @param photoCodeImg
 * @param type
 *            新建类型 3是新建签章 2是新建证书1修改
 * @param uiModel
 * @return
 */
@RequestMapping(method = RequestMethod.POST, value = "/{type}", produces = "text/html")
public String update(@Valid EvidenceCertificate configuration, @RequestParam(value = "photoCodeImg", required = false) String photoCodeImg, @PathVariable("type") int type, Model uiModel) {
    if (type == 1) {
        // System.out.println("新建签章" + configuration.getSignatureType());
        // 获取证书信息
        EvidenceCertificate econfiguration = certificateService.selectById(configuration.getId());
        EvidenceSecretKey secretkey = new EvidenceSecretKey();
        try {
            if (StringUtils.isNotEmpty(photoCodeImg)) {
                // 获取密钥信息
                secretkey = sqlSession.selectOne("com.itrus.portal.db.EvidenceSecretKeyMapper.selectByPrimaryKey", econfiguration.getEvidenceSecretKey());
                File imgDir = filePathUtils.getEnterpriseFile(secretkey.getAlias());
                File frontImg = filePathUtils.saveImg(imgDir, null, photoCodeImg, IMG_DEFAULT_TYPE, IMG_NAME_VERIFY);
                if (frontImg != null && frontImg.isFile()) {
                    configuration.setPhotoCodeImg(frontImg.getName());
                    configuration.setPhotoCodeImgHash(HMACSHA1.genSha1HashOfFile(frontImg));
                }
            }
            if (configuration.getId() == null) {
                certificateService.insert(configuration);
            } else {
                String s = String.valueOf(econfiguration.getEvidenceSecretKey());
                Long keyid = Long.valueOf(s);
                EvidenceSecretKey secret = secrtkey.selectById(keyid);
                boolean is = certificateService.setSeal(secret.getAlias(), photoCodeImg);
                if (is) {
                    certificateService.update(configuration);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            String oper = "修改签章失败";
            String info = "错误原因:" + e.toString();
            LogUtil.evidencelog(sqlSession, null, oper, info);
            error = "修改签章失败";
            return "redirect:/certificate/" + configuration.getId() + "/" + 3;
        }
        if (econfiguration.getIsCertificate() == null || econfiguration.getIsCertificate() != 1) {
            JSONObject ret_data = null;
            ret_data = JSONObject.parseObject(configuration.getSubject());
            String cn = ret_data.getString("userName");
            String ou = ret_data.getString("userOrgunit");
            // String emali = ret_data.getString("EMAILADDRESS");
            String O = ret_data.getString("userOrganization");
            String dn = "CN=" + cn + "OU=" + ou + "O=" + O;
            String csr = certificateService.genCsr(secretkey.getAlias(), configuration.getArithmetic(), dn);
            if (csr != null) {
                RaAccount ra = sqlSession.selectOne("com.itrus.portal.db.RaAccountMapper.selectByPrimaryKey", configuration.getRaAccount());
                CertUtlis certutil = new CertUtlis();
                // UserInfo rauserinfo = new UserInfo();
                // Weibo类在下边定义
                UserInfo rauserinfo = JSON.parseObject(configuration.getSubject(), UserInfo.class);
                // System.out.println(rauserinfo.getUserAdditionalField1()+rauserinfo.getUserName());
                // UserInfo = (UserInfo)JSONObject.toBean(ret_data,UserInfo.class);//将建json对象转换为Person对象
                // System.out.println(configuration.getSubject());
                /*	rauserinfo.setUserName(cn);
					rauserinfo.setUserEmail(emali);
					rauserinfo.setUserAdditionalField1(ou);
					rauserinfo.setUserOrganization(O); */
                // 证书有效期
                Integer certValidity = 7;
                if ("0".equals(configuration.getPeriod())) {
                    certValidity = null;
                } else if (1 == configuration.getPeriod()) {
                    certValidity = 365 * 1 + 1;
                } else if (3 == configuration.getPeriod()) {
                    certValidity = 365 * 3 + 1;
                } else if (5 == configuration.getPeriod()) {
                    certValidity = 365 * 5 + 2;
                } else if (10 == configuration.getPeriod()) {
                    certValidity = 365 * 10 + 2;
                }
                // 调用RA
                CertInfo racertinfo = null;
                try {
                    if (ra.getAaPassword() != null) {
                        ra.setAaPassword(AESencrp.decrypt(ra.getAaPassword(), dbEncKey));
                    }
                    racertinfo = certutil.enrollCertByWS(csr, ra, rauserinfo, certValidity);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    String oper = "RA调用失败";
                    String info = "错误原因:" + e.toString();
                    LogUtil.evidencelog(sqlSession, null, oper, info);
                    error = "RA调用失败";
                    return "redirect:/certificate/" + configuration.getId() + "/" + 3;
                }
                if (racertinfo != null) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
                    EvidenceCert cert = new EvidenceCert();
                    cert.setCertBase64(racertinfo.getCertSignBuf());
                    cert.setCreateTime(new Date());
                    cert.setCertSerialnumber(racertinfo.getCertSerialNumber());
                    cert.setIssuerdn(racertinfo.getCertIssuerDn());
                    cert.setSubjectdn(racertinfo.getCertSubjectDn());
                    try {
                        configuration.setStartTime(sdf.parse(racertinfo.getCertNotBefore()));
                        configuration.setEndTime(sdf.parse(racertinfo.getCertNotAfter()));
                        cert.setStartTime(sdf.parse(racertinfo.getCertNotBefore()));
                        cert.setEndTime(sdf.parse(racertinfo.getCertNotAfter()));
                    } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    cert.setCreateTime(new Date());
                    sqlSession.insert("com.itrus.portal.db.EvidenceCertMapper.insert", cert);
                    configuration.setCert(cert.getId().toString());
                    configuration.setCertp7(racertinfo.getCertSignBufP7());
                    configuration.setCertSerialnumber(racertinfo.getCertSerialNumber());
                    boolean is = certificateService.setCertitifate(secretkey.getAlias(), racertinfo.getCertSignBuf(), racertinfo.getCertSignBufP7());
                    if (is) {
                        if ("0".equals(configuration.getArithmetic())) {
                            configuration.setArithmetic(null);
                        }
                        if (StringUtils.isNotEmpty(configuration.getSubject())) {
                            configuration.setSubject(configuration.getSubject());
                        }
                        String s = String.valueOf(secretkey.getId());
                        int keyid = Integer.parseInt(s);
                        configuration.setEvidenceSecretKey(keyid);
                        configuration.setCreateTime(new Date());
                        configuration.setCreator(getAdmin().getName());
                        certificateService.update(configuration);
                        configuration.setSignatureType(2);
                        String oper = "证书产生成功";
                        String info = "证书名称:" + configuration.getCertificateName();
                        LogUtil.evidencelog(sqlSession, null, oper, info);
                    }
                }
            } else {
                error = "csr产生失败";
                return "redirect:/certificate/" + configuration.getId() + "/" + 3;
            }
        }
    } else if (type == 3) {
        EvidenceCertificate econfiguration = certificateService.selectById(configuration.getId());
        EvidenceSecretKey secretkey = new EvidenceSecretKey();
        try {
            if (StringUtils.isNotEmpty(photoCodeImg)) {
                // 获取密钥信息
                secretkey = sqlSession.selectOne("com.itrus.portal.db.EvidenceSecretKeyMapper.selectByPrimaryKey", econfiguration.getEvidenceSecretKey());
                File imgDir = filePathUtils.getEnterpriseFile(secretkey.getAlias());
                File frontImg = filePathUtils.saveImg(imgDir, null, photoCodeImg, IMG_DEFAULT_TYPE, IMG_NAME_VERIFY);
                if (frontImg != null && frontImg.isFile()) {
                    configuration.setPhotoCodeImg(frontImg.getName());
                    configuration.setPhotoCodeImgHash(HMACSHA1.genSha1HashOfFile(frontImg));
                }
            }
            if (configuration.getId() == null) {
                certificateService.insert(configuration);
            } else {
                String s = String.valueOf(econfiguration.getEvidenceSecretKey());
                Long keyid = Long.valueOf(s);
                EvidenceSecretKey secret = secrtkey.selectById(keyid);
                boolean is = certificateService.setSeal(secret.getAlias(), photoCodeImg);
                if (is) {
                    certificateService.update(configuration);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            String oper = "新建签章失败";
            String info = "错误原因:" + e.toString();
            LogUtil.evidencelog(sqlSession, null, oper, info);
            error = "新建签章失败";
            return "redirect:/certificate/" + configuration.getId() + "/" + 2;
        }
    } else {
        // System.out.println("新建证书");
        EvidenceSecretKey secret = new EvidenceSecretKey();
        // List<EvidenceSecretKey> list = secrtkey.selecttype(configuration.getKeyType());
        // log.error("list="+list.size());
        // if(econfiguration.getIsCertificate()!=null && econfiguration.getIsCertificate()==1){
        /*if (list != null && list.size() != 0) {
					for (EvidenceSecretKey e : list) {
						EvidenceCertificate certificate = certificateService.selectone(e.getId());
						if (certificate == null) {
							secret.setAlias(e.getAlias());
							secret.setId(e.getId());
							break;
						}
					}
					if (StringUtils.isEmpty(secret.getAlias())) {
						List<EvidenceSecretKey> secter = secrtkey.certufucateInterface(getAdmin().getName());
						//List<EvidenceSecretKey> lists = secrtkey.selecttype(configuration.getKeyType());
						if (secter != null) {
							for (EvidenceSecretKey e : secter) {
								EvidenceCertificate certificate = certificateService.selectone(e.getId());
								if (certificate == null) {
									secret.setAlias(e.getAlias());
									secret.setId(e.getId());
									break;
								}
							}
						}
					}
				} else */
        {
            /*EvidenceSecretKey*/
            secret = secrtkey.certufucateInterface(getAdmin().getName(), configuration.getKeyType());
        // List<EvidenceSecretKey> lists = secrtkey.selecttype(configuration.getKeyType());
        /*if (secter != null) {
						for (EvidenceSecretKey e : secter) {
							EvidenceCertificate certificate = certificateService.selectone(e.getId());
							if (certificate == null) {
								secret.setAlias(e.getAlias());
								secret.setId(e.getId());
								break;
							}
						}
					}*/
        }
        /*	}else{
				 secret = sqlSession.selectOne(
						"com.itrus.portal.db.EvidenceSecretKeyMapper.selectByPrimaryKey",
						econfiguration.getEvidenceSecretKey());
			}*/
        JSONObject ret_data = null;
        ret_data = JSONObject.parseObject(configuration.getSubject());
        String cn = ret_data.getString("userName");
        String ou = ret_data.getString("userOrgunit");
        // String emali = ret_data.getString("EMAILADDRESS");
        String O = ret_data.getString("userOrganization");
        String dn = "CN=" + cn + "OU=" + ou + "O=" + O;
        log.error("Alias=" + secret.getAlias() + ",Arithmetic=" + configuration.getArithmetic());
        String csr = certificateService.genCsr(secret.getAlias(), configuration.getArithmetic(), dn);
        log.error("csr=" + csr);
        if (csr != null) {
            RaAccount ra = sqlSession.selectOne("com.itrus.portal.db.RaAccountMapper.selectByPrimaryKey", configuration.getRaAccount());
            CertUtlis certutil = new CertUtlis();
            // UserInfo rauserinfo = new UserInfo();
            // System.out.println(configuration.getSubject());
            // Weibo类在下边定义
            UserInfo rauserinfo = JSON.parseObject(configuration.getSubject(), UserInfo.class);
            // System.out.println(rauserinfo.getUserAdditionalField1()+rauserinfo.getUserName());
            /*rauserinfo.setUserName(cn);
				rauserinfo.setUserEmail(emali);
				rauserinfo.setUserAdditionalField1(ou);
				rauserinfo.setUserOrganization(O);*/
            // 证书有效期
            Integer certValidity = 7;
            if ("0".equals(configuration.getPeriod())) {
                certValidity = null;
            } else if (1 == configuration.getPeriod()) {
                certValidity = 365 * 1 + 1;
            } else if (3 == configuration.getPeriod()) {
                certValidity = 365 * 3 + 1;
            } else if (5 == configuration.getPeriod()) {
                certValidity = 365 * 5 + 2;
            } else if (10 == configuration.getPeriod()) {
                certValidity = 365 * 10 + 2;
            }
            // 调用RA
            CertInfo racertinfo = null;
            try {
                if (ra.getAaPassword() != null) {
                    ra.setAaPassword(AESencrp.decrypt(ra.getAaPassword(), dbEncKey));
                }
                racertinfo = certutil.enrollCertByWS(csr, ra, rauserinfo, certValidity);
                log.error("racertinfo=" + racertinfo);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                String oper = "RA调用失败";
                String info = "错误原因:" + e.toString();
                LogUtil.evidencelog(sqlSession, null, oper, info);
                uiModel.addAttribute("error", "RA调用失败");
                return "certificate/create";
            }
            if (racertinfo != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
                EvidenceCert cert = new EvidenceCert();
                cert.setCertBase64(racertinfo.getCertSignBuf());
                cert.setCreateTime(new Date());
                cert.setCertSerialnumber(racertinfo.getCertSerialNumber());
                cert.setIssuerdn(racertinfo.getCertIssuerDn());
                cert.setSubjectdn(racertinfo.getCertSubjectDn());
                cert.setCreateTime(new Date());
                try {
                    configuration.setStartTime(sdf.parse(racertinfo.getCertNotBefore()));
                    configuration.setEndTime(sdf.parse(racertinfo.getCertNotAfter()));
                    cert.setStartTime(sdf.parse(racertinfo.getCertNotBefore()));
                    cert.setEndTime(sdf.parse(racertinfo.getCertNotAfter()));
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                sqlSession.insert("com.itrus.portal.db.EvidenceCertMapper.insert", cert);
                configuration.setCert(cert.getId().toString());
                // configuration.setCert(racertinfo.getCertSignBuf());
                configuration.setCertp7(racertinfo.getCertSignBufP7());
                configuration.setCertSerialnumber(racertinfo.getCertSerialNumber());
                /*try {
						configuration.setStartTime(sdf.parse(racertinfo.getCertNotBefore()));
						configuration.setEndTime(sdf.parse(racertinfo.getCertNotAfter()));
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}*/
                boolean is = certificateService.setCertitifate(secret.getAlias(), racertinfo.getCertSignBuf(), racertinfo.getCertSignBufP7());
                if (is) {
                    if ("0".equals(configuration.getArithmetic())) {
                        configuration.setArithmetic(null);
                    }
                    if (StringUtils.isNotEmpty(configuration.getSubject())) {
                        configuration.setSubject(configuration.getSubject());
                    }
                    String s = String.valueOf(secret.getId());
                    int keyid = Integer.parseInt(s);
                    configuration.setEvidenceSecretKey(keyid);
                    configuration.setCreateTime(new Date());
                    configuration.setCreator(getAdmin().getName());
                    certificateService.insert(configuration);
                    String oper = "证书产生成功";
                    String info = "证书名称:" + configuration.getCertificateName();
                    LogUtil.evidencelog(sqlSession, null, oper, info);
                    EvidenceCertificateExample certE = new EvidenceCertificateExample();
                    EvidenceCertificateExample.Criteria tificate = certE.createCriteria();
                    tificate.andEvidenceSecretKeyEqualTo(keyid);
                    configuration = sqlSession.selectOne("com.itrus.portal.db.EvidenceCertificateMapper.selectByExample", certE);
                }
            }
        } else {
            uiModel.addAttribute("error", "csr产生失败");
            return "certificate/create";
        }
    }
    return "redirect:/certificate/" + configuration.getId() + "/" + 1;
// return "redirect:/certificate/show/"+configuration.getId()+"/"+1;
// return "redirect:/certificate";
}
Also used : CertInfo(cn.topca.tca.ra.service.CertInfo) UserInfo(cn.topca.tca.ra.service.UserInfo) EvidenceSecretKey(com.itrus.portal.db.EvidenceSecretKey) ParseException(java.text.ParseException) IOException(java.io.IOException) Date(java.util.Date) CertUtlis(com.itrus.portal.utils.CertUtlis) EvidenceCert(com.itrus.portal.db.EvidenceCert) JSONObject(com.alibaba.fastjson.JSONObject) RaAccount(com.itrus.portal.db.RaAccount) EvidenceCertificateExample(com.itrus.portal.db.EvidenceCertificateExample) EvidenceCertificate(com.itrus.portal.db.EvidenceCertificate) ParseException(java.text.ParseException) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 8 with EvidenceCertificate

use of com.itrus.portal.db.EvidenceCertificate in project portal by ixinportal.

the class CertificateController method show.

/**
 * 跳转方法,查看详情和配置签章
 *
 * @param id
 * @param type
 *            区分跳转的页面
 * @param uiModel
 * @return
 */
@RequestMapping(value = "/{id}/{type}", produces = "text/html")
public String show(@PathVariable("id") Long id, @PathVariable("type") int type, Model uiModel) {
    EvidenceCertificate configuration = certificateService.selectById(id);
    if (configuration != null && configuration.getRaAccount() != null) {
        RaAccount ra = raAccount.getRaAccount(Long.valueOf(configuration.getRaAccount()));
        List<RaAccount> ras = sqlSession.selectList("com.itrus.portal.db.RaAccountMapper.selectByExample");
        EvidenceSecretKey secretkey = sqlSession.selectOne("com.itrus.portal.db.EvidenceSecretKeyMapper.selectByPrimaryKey", configuration.getEvidenceSecretKey());
        uiModel.addAttribute("ras", ras);
        uiModel.addAttribute("ra", ra);
        uiModel.addAttribute("secretkey", secretkey);
        uiModel.addAttribute("error", error);
        error = null;
    }
    uiModel.addAttribute("configuration", configuration);
    if (type == 1) {
        return "certificate/show";
    } else if (type == 2) {
        return "certificate/configure";
    } else {
        return "certificate/update";
    }
}
Also used : RaAccount(com.itrus.portal.db.RaAccount) EvidenceCertificate(com.itrus.portal.db.EvidenceCertificate) EvidenceSecretKey(com.itrus.portal.db.EvidenceSecretKey) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 9 with EvidenceCertificate

use of com.itrus.portal.db.EvidenceCertificate in project portal by ixinportal.

the class CertificateController method loadImg.

/**
 * 得到图片
 *
 * @param id
 * @param response
 * @return
 */
@RequestMapping(value = "/img/{id}")
public String loadImg(@PathVariable("id") Long id, HttpServletResponse response) {
    String img = null;
    OutputStream os = null;
    FileInputStream fis = null;
    File file = null;
    try {
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        EvidenceCertificate configuration = certificateService.selectById(id);
        img = configuration.getPhotoCodeImg();
        EvidenceSecretKey secretkey = sqlSession.selectOne("com.itrus.portal.db.EvidenceSecretKeyMapper.selectByPrimaryKey", configuration.getEvidenceSecretKey());
        file = filePathUtils.getBillFile(secretkey.getAlias());
        if (configuration == null && configuration == null) {
            return "status403";
        }
        if (img == null) {
            return "status403";
        }
        if (!file.exists()) {
            file.mkdir();
        }
        File imgFile = new File(file, img);
        fis = new FileInputStream(imgFile);
        byte[] bb = IOUtils.toByteArray(fis);
        os = response.getOutputStream();
        os.write(bb);
        os.flush();
    } catch (IOException e) {
        // 未找到
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 关闭流!
        try {
            if (null != fis) {
                fis.close();
            }
            if (null != os) {
                os.close();
            }
        } catch (IOException e) {
        }
    }
    return null;
}
Also used : OutputStream(java.io.OutputStream) EvidenceCertificate(com.itrus.portal.db.EvidenceCertificate) IOException(java.io.IOException) File(java.io.File) EvidenceSecretKey(com.itrus.portal.db.EvidenceSecretKey) FileInputStream(java.io.FileInputStream) ParseException(java.text.ParseException) IOException(java.io.IOException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 10 with EvidenceCertificate

use of com.itrus.portal.db.EvidenceCertificate in project portal by ixinportal.

the class HisCertificateController method savepdf.

@RequestMapping(params = "uploadPDF", method = RequestMethod.POST, produces = "text/html")
public String savepdf(MultipartFile excelFile, int id, int type, HttpServletRequest request, Model uiModel) throws Exception {
    JSONObject ret_data = null;
    BufferedInputStream bin = null;
    ByteArrayOutputStream baos = null;
    BufferedOutputStream bout = null;
    String fileName = excelFile.getOriginalFilename();
    // 文件类型
    String fileType = FilenameUtils.getExtension(fileName);
    if ((!fileType.toLowerCase().equals("pdf"))) {
        error = "上传失败,上传的文件不是以‘.pdf’文件名结尾";
        return "redirect:/hiscertificate/showpdf/" + id + "/" + type;
    }
    // 得到出征信息
    EvidenceHisCertificateExample hiscer = new EvidenceHisCertificateExample();
    EvidenceHisCertificateExample.Criteria tificate = hiscer.createCriteria();
    tificate.andSerialnumberEqualTo(contractNumber);
    EvidenceHisCertificate hisCertificate = sqlSession.selectOne("com.itrus.portal.db.EvidenceHisCertificateMapper.selectByExample", hiscer);
    // 得到出证关系表
    EvidenceHisRelationshipExample hisrelation = new EvidenceHisRelationshipExample();
    EvidenceHisRelationshipExample.Criteria shipEx = hisrelation.createCriteria();
    shipEx.andHisCertificateEqualTo(hisCertificate.getId());
    List<EvidenceHisRelationship> hisrelationship = sqlSession.selectList("com.itrus.portal.db.EvidenceHisRelationshipMapper.selectByExample", hisrelation);
    try {
        // 建立读取文件的文件输出流
        // fin = new FileInputStream(excelFile.getName());
        // 在文件输出流上安装节点流(更大效率读取)
        // 读取文件流
        bin = new BufferedInputStream(excelFile.getInputStream());
        // 创建一个新的 byte 数组输出流,它具有指定大小的缓冲区容量
        baos = new ByteArrayOutputStream();
        // 创建一个新的缓冲输出流,以将数据写入指定的底层输出流
        bout = new BufferedOutputStream(baos);
        byte[] buffer = new byte[1024];
        int len = bin.read(buffer);
        while (len != -1) {
            bout.write(buffer, 0, len);
            len = bin.read(buffer);
        }
        // 刷新此输出流并强制写出所有缓冲的输出字节,必须这行代码,否则有可能有问题
        bout.flush();
        byte[] bytes = baos.toByteArray();
        // sun公司的API
        // return encoder.encodeBuffer(bytes).trim();
        // apache公司的API
        String base64 = Base64.encodeBase64String(bytes);
        RealNameAuthentication realNameAuthentication = CacheCustomer.getAUTH_CONFIG_MAP().get(2);
        if (realNameAuthentication == null) {
            realNameAuthentication = realNameAuthenticationSerivce.getRealNameAuthenticationByTwo();
        }
        if (realNameAuthentication == null) {
            error = "无服务路径";
            return "redirect:/hiscertificate/showpdf/" + id + "/" + type;
        }
        // 得到服务编码
        AppService appservice = appService.selectById(hisCertificate.getHisAppService());
        // 得到出证服务配置
        EvidenceOutServiceConfigExample saveService = new EvidenceOutServiceConfigExample();
        EvidenceOutServiceConfigExample.Criteria saveServiceEx = saveService.createCriteria();
        saveServiceEx.andAppServiceEqualTo(appservice.getId());
        EvidenceOutServiceConfig outService = sqlSession.selectOne("com.itrus.portal.db.EvidenceOutServiceConfigMapper.selectByExample", saveService);
        // 得到出证名称
        if (outService == null) {
            error = "无服务配置";
            return "redirect:/hiscertificate/showpdf/" + id + "/" + type;
        }
        // 得到证书信息
        EvidenceCertificate certificate = sqlSession.selectOne("com.itrus.portal.db.EvidenceCertificateMapper.selectByPrimaryKey", outService.getEvidenceCertificate());
        if (certificate == null) {
            error = "无证书信息";
            return "redirect:/hiscertificate/showpdf/" + id + "/" + type;
        }
        // 得到密钥信息
        EvidenceSecretKey secrerkey = sqlSession.selectOne("com.itrus.portal.db.EvidenceSecretKeyMapper.selectByPrimaryKey", certificate.getEvidenceSecretKey());
        EvidenceEnclosure enclosure = new EvidenceEnclosure();
        // 得到签章位置配置信息
        EvidenceSignetPlaceConfigExample signet = new EvidenceSignetPlaceConfigExample();
        EvidenceSignetPlaceConfigExample.Criteria palace = signet.createCriteria();
        palace.andEvidenceOutServiceConfigEqualTo(outService.getId());
        List<EvidenceSignetPlaceConfig> configlist = sqlSession.selectList("com.itrus.portal.db.EvidenceSignetPlaceConfigMapper.selectByExample", signet);
        // 得到接口路径
        String urlAgent = realNameAuthentication.getRealNameddress() + PDF_SIGN;
        Map<String, Object> paramsAgent = new HashMap<String, Object>();
        // 参数信息
        paramsAgent.put("alias", secrerkey.getAlias());
        paramsAgent.put("pdfContent", base64);
        for (EvidenceSignetPlaceConfig config : configlist) {
            // 获取签章信息
            List<Map> list = new ArrayList<Map>();
            Map<String, String> map = new HashMap<String, String>();
            if (config != null) {
                if (config.getType() == 2) {
                    // 参数信息
                    map.put("y", config.getDistanceToDown());
                    // 参数信息
                    map.put("width", config.getWidthOfImage());
                    // 参数信息
                    map.put("height", config.getHeightOfImage());
                    list.add(map);
                    paramsAgent.put("pagingSeal", JSON.toJSONString(list));
                } else if (config.getType() == 3) {
                    // 参数信息
                    map.put("page", config.getPage());
                    // 参数信息
                    map.put("x", config.getDistanceToLeft());
                    // 参数信息
                    map.put("y", config.getDistanceToDown());
                    // 参数信息
                    map.put("width", config.getWidthOfImage());
                    // 参数信息
                    map.put("height", config.getHeightOfImage());
                    list.add(map);
                    paramsAgent.put("multiPagesSeal", JSON.toJSONString(list));
                } else if (config.getType() == 1) {
                    // 参数信息
                    map.put("keyWord", config.getKeyword());
                    // 参数信息
                    map.put("page", config.getPage());
                    // 参数信息
                    map.put("width", config.getWidthOfImage());
                    // 参数信息
                    map.put("height", config.getHeightOfImage());
                    list.add(map);
                    paramsAgent.put("keyWordSeal", JSON.toJSONString(list));
                }
            }
        }
        boolean isbool = true;
        String signedPdf = null;
        if (outService.getIsAddTimestamp() == 2) {
            isbool = false;
        }
        // 参数信息
        paramsAgent.put("timeStamp", isbool);
        // paramsAgent.put("resultType",2L);//参数信息
        // 调用签章接口返回数据
        String repAgent = HttpClientUtil.postForm(urlAgent, AuthService.getHeader(), paramsAgent);
        // 把数据转换为json格式
        ret_data = JSONObject.parseObject(repAgent);
        if (ret_data.getIntValue("code") != 0) {
            // 判断是否成功
            String oper = "出证报告失败-pdf签章失败";
            String info = "错误原因:" + ret_data.getString("message");
            LogUtil.evidencelog(sqlSession, null, oper, info);
            error = ret_data.getString("message");
            // 修改证据中的出证状态
            for (EvidenceHisRelationship h : hisrelationship) {
                // 得到基本信息表
                EvidenceBasicInformation basic = sqlSession.selectOne("com.itrus.portal.db.EvidenceBasicInformationMapper.selectByPrimaryKey", h.getBasicInformation());
                basic.setStatus(4);
                sqlSession.update("com.itrus.portal.db.EvidenceBasicInformationMapper.updateByPrimaryKey", basic);
            }
            return "redirect:/hiscertificate/showpdf/" + id + "/" + type;
        } else {
            // 证书base编码
            signedPdf = ret_data.getString("signedPdf");
            // 正式系统将hood替换为/**/重的值
            String retpdf = EvidenceSaveServiceApi.storageSave("ST_O", "hood", /*realNameAuthentication.getKeyCode()*/
            hisCertificate.getSerialnumber() + ".pdf", "CT_MESSAGE", signedPdf, null, null, null, null, null, false, null, realNameAuthentication.getRealNameddress());
            // 把数据转换为json格式
            ret_data = JSONObject.parseObject(retpdf);
            if (ret_data.getInteger("code") == 0) {
                // 获取证据附件表
                EvidenceEnclosureExample envlosureE = new EvidenceEnclosureExample();
                EvidenceEnclosureExample.Criteria envlosureEx = envlosureE.createCriteria();
                envlosureEx.andSerialnumberEqualTo(hisCertificate.getSerialnumber());
                envlosureEx.andPdfTypeEqualTo("4");
                EvidenceEnclosure envlosure = sqlSession.selectOne("com.itrus.portal.db.EvidenceEnclosureMapper.selectByExample", envlosureE);
                if (envlosure != null && envlosure.getPdfType() != null) {
                    envlosure.setPdfType("4");
                    envlosure.setEvidenceSn(null);
                    envlosure.setSerialnumber(hisCertificate.getSerialnumber());
                    envlosure.setType("ST_E");
                    envlosure.setContentType("CT_BASE64_DATA");
                    envlosure.setBucketName(realNameAuthentication.getKeyCode());
                    envlosure.setObjectName(fileName);
                    envlosure.setAlias(secrerkey.getAlias());
                    envlosure.setFilesize(null);
                    envlosure.setApplicationTime(new Date());
                    envlosure.setFixationTime(new Date());
                    envlosure.setSaveFactor(null);
                    envlosure.setBuid(ret_data.getString("buid").toString());
                    // ret_data.remove("saveFactor");
                    sqlSession.update("com.itrus.portal.db.EvidenceEnclosureMapper.updateByPrimaryKey", envlosure);
                } else {
                    enclosure.setPdfType("4");
                    enclosure.setEvidenceSn(null);
                    enclosure.setSerialnumber(hisCertificate.getSerialnumber());
                    enclosure.setType("ST_E");
                    enclosure.setContentType("CT_BASE64_DATA");
                    enclosure.setBucketName(realNameAuthentication.getKeyCode());
                    enclosure.setObjectName(fileName);
                    enclosure.setAlias(secrerkey.getAlias());
                    enclosure.setFilesize(null);
                    enclosure.setApplicationTime(new Date());
                    enclosure.setFixationTime(new Date());
                    enclosure.setSaveFactor(null);
                    enclosure.setBuid(ret_data.getString("buid").toString());
                    // ret_data.remove("saveFactor");
                    sqlSession.insert("com.itrus.portal.db.EvidenceEnclosureMapper.insert", enclosure);
                }
                hisCertificate.setHisTime(new Date());
                hisCertificate.setHisway("2");
                hisCertificate.setHisState("0");
                hisCertificate.setOutState(0);
                sqlSession.update("com.itrus.portal.db.EvidenceHisCertificateMapper.updateByPrimaryKey", hisCertificate);
                // 修改证据中的出证状态
                for (EvidenceHisRelationship h : hisrelationship) {
                    // 得到基本信息表
                    EvidenceBasicInformation basic = sqlSession.selectOne("com.itrus.portal.db.EvidenceBasicInformationMapper.selectByPrimaryKey", h.getBasicInformation());
                    basic.setStatus(2);
                    sqlSession.update("com.itrus.portal.db.EvidenceBasicInformationMapper.updateByPrimaryKey", basic);
                }
                error = "上传pdf成功";
                String oper = "pdf上传成功";
                String info = "存储编号:" + ret_data.getString("buid").toString() + "pdf名称:" + hisCertificate.getSerialnumber();
                LogUtil.evidencelog(sqlSession, null, oper, info);
            }
        }
    } catch (FileNotFoundException e) {
        // 修改证据中的出证状态
        for (EvidenceHisRelationship h : hisrelationship) {
            // 得到基本信息表
            EvidenceBasicInformation basic = sqlSession.selectOne("com.itrus.portal.db.EvidenceBasicInformationMapper.selectByPrimaryKey", h.getBasicInformation());
            basic.setStatus(4);
            sqlSession.update("com.itrus.portal.db.EvidenceBasicInformationMapper.updateByPrimaryKey", basic);
        }
        e.printStackTrace();
        String oper = "pdf上传失败";
        String info = "失败原因:" + e.getMessage();
        LogUtil.evidencelog(sqlSession, null, oper, info);
        error = e.getMessage();
        return "redirect:/hiscertificate/showpdf/" + id + "/" + type;
    } catch (IOException e) {
        // 修改证据中的出证状态
        for (EvidenceHisRelationship h : hisrelationship) {
            // 得到基本信息表
            EvidenceBasicInformation basic = sqlSession.selectOne("com.itrus.portal.db.EvidenceBasicInformationMapper.selectByPrimaryKey", h.getBasicInformation());
            basic.setStatus(4);
            sqlSession.update("com.itrus.portal.db.EvidenceBasicInformationMapper.updateByPrimaryKey", basic);
        }
        e.printStackTrace();
        String oper = "pdf上传失败";
        String info = "失败原因:" + e.getMessage();
        LogUtil.evidencelog(sqlSession, null, oper, info);
        error = e.getMessage();
        return "redirect:/hiscertificate/showpdf/" + id + "/" + type;
    } finally {
        try {
            bin.close();
            // 关闭 ByteArrayOutputStream 无效。此类中的方法在关闭此流后仍可被调用,而不会产生任何
            // IOException
            // 暂时关闭掉
            baos.close();
            bout.close();
        } catch (IOException e) {
            e.printStackTrace();
            error = e.getMessage();
            return "redirect:/hiscertificate/showpdf/" + id + "/" + type;
        }
    }
    return "redirect:/hiscertificate/showpdf/" + id + "/" + type;
}
Also used : HashMap(java.util.HashMap) EvidenceBasicInformation(com.itrus.portal.db.EvidenceBasicInformation) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) EvidenceHisCertificate(com.itrus.portal.db.EvidenceHisCertificate) EvidenceEnclosure(com.itrus.portal.db.EvidenceEnclosure) RealNameAuthentication(com.itrus.portal.db.RealNameAuthentication) EvidenceOutServiceConfig(com.itrus.portal.db.EvidenceOutServiceConfig) EvidenceSignetPlaceConfigExample(com.itrus.portal.db.EvidenceSignetPlaceConfigExample) BufferedInputStream(java.io.BufferedInputStream) EvidenceCertificate(com.itrus.portal.db.EvidenceCertificate) BufferedOutputStream(java.io.BufferedOutputStream) AppService(com.itrus.portal.db.AppService) EvidenceOutServiceConfigExample(com.itrus.portal.db.EvidenceOutServiceConfigExample) EvidenceSignetPlaceConfig(com.itrus.portal.db.EvidenceSignetPlaceConfig) EvidenceHisRelationship(com.itrus.portal.db.EvidenceHisRelationship) EvidenceEnclosureExample(com.itrus.portal.db.EvidenceEnclosureExample) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) EvidenceSecretKey(com.itrus.portal.db.EvidenceSecretKey) EvidenceHisRelationshipExample(com.itrus.portal.db.EvidenceHisRelationshipExample) Date(java.util.Date) JSONObject(com.alibaba.fastjson.JSONObject) EvidenceHisCertificateExample(com.itrus.portal.db.EvidenceHisCertificateExample) JSONObject(com.alibaba.fastjson.JSONObject) Map(java.util.Map) HashMap(java.util.HashMap) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

EvidenceCertificate (com.itrus.portal.db.EvidenceCertificate)13 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)10 HashMap (java.util.HashMap)6 EvidenceSecretKey (com.itrus.portal.db.EvidenceSecretKey)5 JSONObject (com.alibaba.fastjson.JSONObject)4 EvidenceServiceConfiguration (com.itrus.portal.db.EvidenceServiceConfiguration)4 Date (java.util.Date)4 EvidenceBasicInformation (com.itrus.portal.db.EvidenceBasicInformation)3 EvidenceSignetPlaceConfig (com.itrus.portal.db.EvidenceSignetPlaceConfig)3 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 Map (java.util.Map)3 AppService (com.itrus.portal.db.AppService)2 EvidenceCertificateExample (com.itrus.portal.db.EvidenceCertificateExample)2 EvidenceClientSignature (com.itrus.portal.db.EvidenceClientSignature)2 EvidenceEnclosure (com.itrus.portal.db.EvidenceEnclosure)2 EvidenceEnclosureExample (com.itrus.portal.db.EvidenceEnclosureExample)2 EvidenceOutTemplate (com.itrus.portal.db.EvidenceOutTemplate)2 RaAccount (com.itrus.portal.db.RaAccount)2 EvidenceCertificationChargingHandler (com.itrus.portal.evidence.service.EvidenceCertificationChargingHandler)2