20220315-bugs

This commit is contained in:
fuqingji
2022-03-21 16:15:51 +08:00
parent 346ec02cb0
commit 06d2b32c77
12 changed files with 262 additions and 242 deletions

View File

@ -1,12 +1,6 @@
package com.chinaunicom.mall.ebtp.extend.bizshortmessageemail.service.impl;
import java.io.*;
import java.nio.file.Files;
import java.time.LocalDateTime;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.web.multipart.MultipartFile;
import cn.hutool.core.exceptions.ExceptionUtil;
import com.chinaunicom.mall.ebtp.common.base.entity.BaseResponse;
import com.chinaunicom.mall.ebtp.extend.bizshortmessageemail.client.NotificationFeignClient;
import com.chinaunicom.mall.ebtp.extend.bizshortmessageemail.entity.BizSendEmailVO;
@ -15,18 +9,25 @@ import com.chinaunicom.mall.ebtp.extend.bizshortmessageemail.entity.EshopMailPen
import com.chinaunicom.mall.ebtp.extend.bizshortmessageemail.entity.EshopSmsPendingPO;
import com.chinaunicom.mall.ebtp.extend.bizshortmessageemail.enums.ExceptionEnum;
import com.chinaunicom.mall.ebtp.extend.bizshortmessageemail.service.BizSmsEmailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.annotation.Resource;
import java.io.*;
import java.nio.file.Files;
/**
* @author Neo
*/
@Service
@Slf4j
public class BizSmsEmailServiceImpl implements BizSmsEmailService {
private static final Logger logger = LoggerFactory.getLogger(BizSmsEmailServiceImpl.class);
@ -42,7 +43,7 @@ public class BizSmsEmailServiceImpl implements BizSmsEmailService {
po.setSendUid(msgVO.getSendUid());
po.setSendUName(msgVO.getSendUName());
if (msgVO.getMutiMobileNumber() != null && !msgVO.getMutiMobileNumber().isEmpty()) {
po.setStrMobileNumber(StringUtils.join(msgVO.getMutiMobileNumber().toArray(),","));
po.setStrMobileNumber(StringUtils.join(msgVO.getMutiMobileNumber().toArray(), ","));
} else {
po.setStrMobileNumber(msgVO.getStrMobileNumberr());
}
@ -75,7 +76,7 @@ public class BizSmsEmailServiceImpl implements BizSmsEmailService {
po.setFileType(emailVO.getFileType());
if ("1".equals(emailVO.getFileType())) {
po.setFileUrl(emailVO.getFileUrl());
} else if ("2".equals(emailVO.getFileType())){
} else if ("2".equals(emailVO.getFileType())) {
po.setFile(this.getFile());
}
@ -88,28 +89,27 @@ public class BizSmsEmailServiceImpl implements BizSmsEmailService {
}
/**
*
* @Description 返回MultipartFile文件
* @return org.springframework.web.multipart.MultipartFile
* @Description 返回MultipartFile文件
* @date 2019/1/5 11:08
* @auther dell
*/
private MultipartFile getFile() throws IOException {
String filePath = "D:\\文档\\3.0能力间调用接口-通知中心.docx";
File file = new File(filePath);
FileItem fileItem = new DiskFileItem("copyfile.txt", Files.probeContentType(file.toPath()),false,file.getName(),(int)file.length(),file.getParentFile());
FileItem fileItem = new DiskFileItem("copyfile.txt", Files.probeContentType(file.toPath()), false, file.getName(), (int) file.length(), file.getParentFile());
byte[] buffer = new byte[4096];
int n;
try (InputStream inputStream = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()){
while ( (n = inputStream.read(buffer,0,4096)) != -1){
os.write(buffer,0,n);
try (InputStream inputStream = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) {
while ((n = inputStream.read(buffer, 0, 4096)) != -1) {
os.write(buffer, 0, n);
}
//也可以用IOUtils.copy(inputStream,os);
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
System.out.println(multipartFile.getName());
return multipartFile;
}catch (IOException e){
e.printStackTrace();
} catch (IOException e) {
log.info(ExceptionUtil.stacktraceToString(e));
}
return null;
}

View File

@ -108,12 +108,12 @@ public class Config {
public static final String LIFECYCLE_INITREQUIREDDEFAULT = "org.hyperledger.fabric.com.chinaunicom.ebtp.mall.cloud.attachment.sdk.lifecycle.initRequiredDefault"; //ORG_HYPERLEDGER_FABRIC_SDK_LIFECYCLE_INITREQUIREDDEFAULT
private static Config config;
private static final Properties sdkProperties = new Properties();
private static final AtomicLong count = new AtomicLong(0);
private static final Properties SDK_PROPERTIES = new Properties();
private static final AtomicLong COUNT = new AtomicLong(0);
//Provides a unique id for logging to identify a specific instance.
public String getNextID() {
return "" + count.incrementAndGet();
return "" + COUNT.incrementAndGet();
}
private Config() {
@ -126,7 +126,7 @@ public class Config {
logger.debug(format("Loading configuration from %s and it is present: %b", loadFile.toString(),
loadFile.exists()));
configProps = new FileInputStream(loadFile);
sdkProperties.load(configProps);
SDK_PROPERTIES.load(configProps);
} catch (IOException e) {
logger.warn(format("Failed to load any configuration from: %s. Using toolkit defaults",
@ -200,7 +200,7 @@ public class Config {
defaultProperty(LIFECYCLE_CHAINCODE_VALIDATION_PLUGIN, DEFAULT_NULL);
defaultProperty(LIFECYCLE_INITREQUIREDDEFAULT, DEFAULT_NULL);
final String inLogLevel = sdkProperties.getProperty(LOGGERLEVEL);
final String inLogLevel = SDK_PROPERTIES.getProperty(LOGGERLEVEL);
if (null != inLogLevel) {
@ -232,10 +232,10 @@ public class Config {
*/
private String getProperty(String property) {
if (!sdkProperties.containsKey(property)) {
if (!SDK_PROPERTIES.containsKey(property)) {
logger.warn(format("No configuration value found for '%s'", property));
}
String ret = sdkProperties.getProperty(property);
String ret = SDK_PROPERTIES.getProperty(property);
if (DEFAULT_NULL.equals(ret)) {
ret = null;
}
@ -246,15 +246,15 @@ public class Config {
String ret = System.getProperty(key);
if (ret != null) {
sdkProperties.put(key, ret);
SDK_PROPERTIES.put(key, ret);
} else {
String envKey = key.toUpperCase().replaceAll("\\.", "_");
ret = System.getenv(envKey);
if (null != ret) {
sdkProperties.put(key, ret);
SDK_PROPERTIES.put(key, ret);
} else {
if (null == sdkProperties.getProperty(key) && value != null) {
sdkProperties.put(key, value);
if (null == SDK_PROPERTIES.getProperty(key) && value != null) {
SDK_PROPERTIES.put(key, value);
}
}
@ -500,7 +500,7 @@ public class Config {
return diagnosticFileDumper;
}
String dd = sdkProperties.getProperty(DIAGNOTISTIC_FILE_DIRECTORY);
String dd = SDK_PROPERTIES.getProperty(DIAGNOTISTIC_FILE_DIRECTORY);
if (dd != null) {
@ -601,6 +601,6 @@ public class Config {
}
return null;
return false;
}
}

View File

@ -46,7 +46,7 @@ public class DiagnosticFileDumper implements Runnable {
private final BlockingQueue<QueEntry> queEntries = new LinkedBlockingQueue<>();
private static DiagnosticFileDumper singleInstance = null;
private static final AtomicInteger counter = new AtomicInteger(0);
private static final AtomicInteger COUNTER = new AtomicInteger(0);
private DiagnosticFileDumper(File directory) {
@ -115,7 +115,7 @@ public class DiagnosticFileDumper implements Runnable {
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss_SSS");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("UTC"));
fileName = prefix + dateFormatGmt.format(new Date()) + "P" + pid + "_" + Thread.currentThread().getId()
+ "_" + counter.addAndGet(1) + "." + ext;
+ "_" + COUNTER.addAndGet(1) + "." + ext;
fileName = fileName.replaceAll("\\:", "-"); // colon is bad for windows.
new QueEntry(fileName, bytes); //Add to Que let process by async thread.

View File

@ -50,8 +50,8 @@ public final class Utils {
private static final Log logger = LogFactory.getLog(Utils.class);
private static final boolean TRACE_ENABED = logger.isTraceEnabled();
private static final Config config = Config.getConfig();
private static final int MAX_LOG_STRING_LENGTH = config.maxLogStringLength();
private static final Config CONFIG = Config.getConfig();
private static final int MAX_LOG_STRING_LENGTH = CONFIG.maxLogStringLength();
/**
* Generate parameter hash for the given chaincode path,func and args
@ -300,7 +300,8 @@ public final class Utils {
}
Properties props = new Properties();
final Pattern p = Pattern.compile("([^:]+)[:]//([^:]+)[:]([0-9]+)", Pattern.CASE_INSENSITIVE);
final String regex = "([^:]+)[:]//([^:]+)[:]([0-9]+)";
final Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(url);
if (m.matches()) {
props.setProperty("protocol", m.group(1));

View File

@ -59,22 +59,22 @@ import static com.chinaunicom.mall.ebtp.extend.crypconfigure.crypto.helper.Utils
import static java.lang.String.format;
public class CryptoPrimitives implements CryptoSuite {
private static final Log logger = LogFactory.getLog(CryptoPrimitives.class);
private static final Config config = Config.getConfig();
private static final boolean IS_TRACE_LEVEL = logger.isTraceEnabled();
private static final Log LOGGER = LogFactory.getLog(CryptoPrimitives.class);
private static final Config CONFIG = Config.getConfig();
private static final boolean IS_TRACE_LEVEL = LOGGER.isTraceEnabled();
private static final DiagnosticFileDumper diagnosticFileDumper = IS_TRACE_LEVEL
? config.getDiagnosticFileDumper() : null;
private static final DiagnosticFileDumper DIAGNOSTIC_FILE_DUMPER = IS_TRACE_LEVEL
? CONFIG.getDiagnosticFileDumper() : null;
private String curveName;
private CertificateFactory cf;
private Provider SECURITY_PROVIDER;
private String hashAlgorithm = config.getHashAlgorithm();
private int securityLevel = config.getSecurityLevel();
private String CERTIFICATE_FORMAT = config.getCertificateFormat();
private String DEFAULT_SIGNATURE_ALGORITHM = config.getSignatureAlgorithm();
private String hashAlgorithm = CONFIG.getHashAlgorithm();
private int securityLevel = CONFIG.getSecurityLevel();
private String CERTIFICATE_FORMAT = CONFIG.getCertificateFormat();
private String DEFAULT_SIGNATURE_ALGORITHM = CONFIG.getSignatureAlgorithm();
private Map<Integer, String> securityCurveMapping = config.getSecurityCurveMapping();
private Map<Integer, String> securityCurveMapping = CONFIG.getSecurityCurveMapping();
// Following configuration settings are hardcoded as they don't deal with any interactions with Fabric MSP and BCCSP components
// If you wish to make these customizable, follow the logic from setProperties();
@ -87,7 +87,7 @@ public class CryptoPrimitives implements CryptoSuite {
// private int MAC_KEY_BYTE_COUNT = 32;
public CryptoPrimitives() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
String securityProviderClassName = config.getSecurityProviderClassName();
String securityProviderClassName = CONFIG.getSecurityProviderClassName();
SECURITY_PROVIDER = setUpExplicitProvider(securityProviderClassName);
@ -183,7 +183,7 @@ public class CryptoPrimitives implements CryptoSuite {
try {
providerList.add(BouncyCastleProvider.class.newInstance()); // bouncy castle is there always.
} catch (Exception e) {
logger.warn(e);
LOGGER.warn(e);
}
for (Provider provider : providerList) {
@ -220,7 +220,7 @@ public class CryptoPrimitives implements CryptoSuite {
if (ret == null) {
logger.error("Could not convert pem bytes");
LOGGER.error("Could not convert pem bytes");
}
@ -242,10 +242,10 @@ public class CryptoPrimitives implements CryptoSuite {
PemObject po = pr.readPemObject();
PEMParser pem = new PEMParser(new StringReader(new String(pemKey)));
if (po.getType().equals("PRIVATE KEY")) {
if ("PRIVATE KEY".equals(po.getType())) {
pk = new JcaPEMKeyConverter().getPrivateKey((PrivateKeyInfo) pem.readObject());
} else {
logger.trace("Found private key with type " + po.getType());
LOGGER.trace("Found private key with type " + po.getType());
PEMKeyPair kp = (PEMKeyPair) pem.readObject();
pk = new JcaPEMKeyConverter().getPrivateKey(kp.getPrivateKeyInfo());
}
@ -263,13 +263,13 @@ public class CryptoPrimitives implements CryptoSuite {
return false;
}
if (config.extraLogLevel(10)) {
if (null != diagnosticFileDumper) {
if (CONFIG.extraLogLevel(10)) {
if (null != DIAGNOSTIC_FILE_DUMPER) {
String message = "plaintext in hex: " + DatatypeConverter.printHexBinary(plainText) + '\n' +
"signature in hex: " + DatatypeConverter.printHexBinary(signature) + '\n' +
"PEM cert in hex: " + DatatypeConverter.printHexBinary(pemCertificate);
logger.trace("verify : " +
diagnosticFileDumper.createDiagnosticFile(message));
LOGGER.trace("verify : " +
DIAGNOSTIC_FILE_DUMPER.createDiagnosticFile(message));
}
}
@ -293,11 +293,11 @@ public class CryptoPrimitives implements CryptoSuite {
CryptoException ex = new CryptoException("Cannot verify signature. Error is: "
+ e.getMessage() + "\r\nCertificate: "
+ DatatypeConverter.printHexBinary(pemCertificate), e);
logger.error(ex.getMessage(), ex);
LOGGER.error(ex.getMessage(), ex);
throw ex;
} catch (NoSuchAlgorithmException | SignatureException e) {
CryptoException ex = new CryptoException("Cannot verify. Signature algorithm is invalid. Error is: " + e.getMessage(), e);
logger.error(ex.getMessage(), ex);
LOGGER.error(ex.getMessage(), ex);
throw ex;
}
@ -433,9 +433,9 @@ public class CryptoPrimitives implements CryptoSuite {
}
try {
if (config.extraLogLevel(10)) {
if (null != diagnosticFileDumper) {
logger.trace(format("Adding cert to trust store. alias: %s. certificate:", alias) + diagnosticFileDumper.createDiagnosticFile(alias + "cert: " + caCert.toString()));
if (CONFIG.extraLogLevel(10)) {
if (null != DIAGNOSTIC_FILE_DUMPER) {
LOGGER.trace(format("Adding cert to trust store. alias: %s. certificate:", alias) + DIAGNOSTIC_FILE_DUMPER.createDiagnosticFile(alias + "cert: " + caCert.toString()));
}
}
synchronized (certificateSet) {
@ -449,7 +449,7 @@ public class CryptoPrimitives implements CryptoSuite {
}
} catch (KeyStoreException e) {
String emsg = "Unable to add CA certificate to trust store. Error: " + e.getMessage();
logger.error(emsg, e);
LOGGER.error(emsg, e);
throw new CryptoException(emsg, e);
}
}
@ -543,7 +543,7 @@ public class CryptoPrimitives implements CryptoSuite {
return validateCertificate(certificate);
} catch (Exception e) {
logger.error("Cannot validate certificate. Error is: " + e.getMessage() + "\r\nCertificate (PEM, hex): "
LOGGER.error("Cannot validate certificate. Error is: " + e.getMessage() + "\r\nCertificate (PEM, hex): "
+ DatatypeConverter.printHexBinary(certPEM));
return false;
}
@ -573,7 +573,7 @@ public class CryptoPrimitives implements CryptoSuite {
isValidated = true;
} catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchAlgorithmException
| CertificateException | CertPathValidatorException | CryptoException e) {
logger.error("Cannot validate certificate. Error is: " + e.getMessage() + "\r\nCertificate"
LOGGER.error("Cannot validate certificate. Error is: " + e.getMessage() + "\r\nCertificate"
+ cert.toString());
isValidated = false;
}
@ -588,7 +588,7 @@ public class CryptoPrimitives implements CryptoSuite {
* @throws InvalidArgumentException
*/
void setSecurityLevel(final int securityLevel) throws InvalidArgumentException {
logger.trace(format("setSecurityLevel to %d", securityLevel));
LOGGER.trace(format("setSecurityLevel to %d", securityLevel));
if (securityCurveMapping.isEmpty()) {
throw new InvalidArgumentException("Security curve mapping has no entries.");
@ -608,7 +608,7 @@ public class CryptoPrimitives implements CryptoSuite {
String lcurveName = securityCurveMapping.get(securityLevel);
logger.debug(format("Mapped curve strength %d to %s", securityLevel, lcurveName));
LOGGER.debug(format("Mapped curve strength %d to %s", securityLevel, lcurveName));
X9ECParameters params = ECNamedCurveTable.getByName(lcurveName);
//Check if can match curve name to requested strength.
@ -617,7 +617,7 @@ public class CryptoPrimitives implements CryptoSuite {
InvalidArgumentException invalidArgumentException = new InvalidArgumentException(
format("Curve %s defined for security strength %d was not found.", curveName, securityLevel));
logger.error(invalidArgumentException);
LOGGER.error(invalidArgumentException);
throw invalidArgumentException;
}
@ -787,7 +787,7 @@ public class CryptoPrimitives implements CryptoSuite {
return certificationRequestToPEM(p10Builder.build(signer));
} catch (Exception e) {
logger.error(e);
LOGGER.error(e);
throw new InvalidArgumentException(e);
}
@ -905,7 +905,7 @@ public class CryptoPrimitives implements CryptoSuite {
cf = CertificateFactory.getInstance(CERTIFICATE_FORMAT);
} catch (CertificateException e) {
CryptoException ex = new CryptoException("Cannot initialize " + CERTIFICATE_FORMAT + " certificate factory. Error = " + e.getMessage(), e);
logger.error(ex.getMessage(), ex);
LOGGER.error(ex.getMessage(), ex);
throw ex;
}
}
@ -925,12 +925,12 @@ public class CryptoPrimitives implements CryptoSuite {
if (properties.containsKey(Config.SECURITY_CURVE_MAPPING)) {
securityCurveMapping = Config.parseSecurityCurveMappings(properties.getProperty(Config.SECURITY_CURVE_MAPPING));
} else {
securityCurveMapping = config.getSecurityCurveMapping();
securityCurveMapping = CONFIG.getSecurityCurveMapping();
}
final String providerName = properties.containsKey(Config.SECURITY_PROVIDER_CLASS_NAME) ?
properties.getProperty(Config.SECURITY_PROVIDER_CLASS_NAME) :
config.getSecurityProviderClassName();
CONFIG.getSecurityProviderClassName();
try {
SECURITY_PROVIDER = setUpExplicitProvider(providerName);

View File

@ -15,7 +15,6 @@
package com.chinaunicom.mall.ebtp.extend.crypconfigure.crypto.security;
import com.chinaunicom.mall.ebtp.extend.crypconfigure.crypto.exception.CryptoException;
import com.chinaunicom.mall.ebtp.extend.crypconfigure.crypto.exception.InvalidArgumentException;
import com.chinaunicom.mall.ebtp.extend.crypconfigure.crypto.helper.Config;
@ -30,20 +29,20 @@ import java.util.concurrent.ConcurrentHashMap;
* SDK's Default implementation of CryptoSuiteFactory.
*/
public class HLSDKJCryptoSuiteFactory implements CryptoSuiteFactory {
private static final Config config = Config.getConfig();
private static final int SECURITY_LEVEL = config.getSecurityLevel();
private static final String HASH_ALGORITHM = config.getHashAlgorithm();
private static final Config CONFIG = Config.getConfig();
private static final int SECURITY_LEVEL = CONFIG.getSecurityLevel();
private static final String HASH_ALGORITHM = CONFIG.getHashAlgorithm();
private HLSDKJCryptoSuiteFactory() {
}
private static final Map<Properties, CryptoSuite> cache = new ConcurrentHashMap<>();
private static final Map<Properties, CryptoSuite> CACHE = new ConcurrentHashMap<>();
@Override
public CryptoSuite getCryptoSuite(Properties properties) throws CryptoException, InvalidArgumentException {
CryptoSuite ret = cache.get(properties);
CryptoSuite ret = CACHE.get(properties);
if (ret == null) {
try {
CryptoPrimitives cp = new CryptoPrimitives();
@ -54,7 +53,7 @@ public class HLSDKJCryptoSuiteFactory implements CryptoSuiteFactory {
throw new CryptoException(e.getMessage(), e);
}
cache.put(properties, ret);
CACHE.put(properties, ret);
}
@ -85,7 +84,7 @@ public class HLSDKJCryptoSuiteFactory implements CryptoSuiteFactory {
if (null == theFACTORY) {
String cf = config.getDefaultCryptoSuiteFactory();
String cf = CONFIG.getDefaultCryptoSuiteFactory();
if (null == cf || cf.isEmpty() || cf.equals(HLSDKJCryptoSuiteFactory.class.getName())) { // Use this class as the factory.
theFACTORY = HLSDKJCryptoSuiteFactory.instance();

View File

@ -1,5 +1,6 @@
package com.chinaunicom.mall.ebtp.extend.crypconfigure.crypto.service;
import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.chinaunicom.mall.ebtp.extend.crypconfigure.crypto.exception.InvalidArgumentException;
@ -121,11 +122,11 @@ public class CrypServiceImpl {
byte[] crtBytes = crtKey.getBytes();
result = cp.verify(crtBytes, SIGNING_ALGORITHM, signature, plainData);
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
e.printStackTrace();
log.info(ExceptionUtil.stacktraceToString(e));
} catch (InvalidArgumentException e) {
e.printStackTrace();
log.info(ExceptionUtil.stacktraceToString(e));
} catch (com.chinaunicom.mall.ebtp.extend.crypconfigure.crypto.exception.CryptoException e) {
e.printStackTrace();
log.info(ExceptionUtil.stacktraceToString(e));
}
return result;
}

View File

@ -40,12 +40,12 @@ import java.util.*;
/**
* 对数据表 biz_bid_cryp_configure 操作的 serviceImpl
* @author yss
*
* @author yss
*/
@Slf4j
@Service
public class CrypConfigureServiceImpl extends BaseServiceImpl<CrypConfigureMapper,CrypConfigure> implements ICrypConfigureService {
public class CrypConfigureServiceImpl extends BaseServiceImpl<CrypConfigureMapper, CrypConfigure> implements ICrypConfigureService {
@Autowired
private IBlockChainLogService iBlockChainLogService;
@ -56,9 +56,9 @@ public class CrypConfigureServiceImpl extends BaseServiceImpl<CrypConfigureMappe
// 测试 PEM_PATH = "admin_certPrivateNew.pem" CRT_PATH = "adminNew.crt"
// 生产 PEM_PATH = "bidding_certPrivate.pem" CRT_PATH = "bidding.crt"
// 私钥文件路径 - 加密
private static String PEM_PATH = "bidding_certPrivate.pem";
private String PEM_PATH = "bidding_certPrivate.pem";
// 证书文件路径 - 解密
private static String CRT_PATH = "bidding.crt";
private String CRT_PATH = "bidding.crt";
@Value("${mconfig.bss.app-id}")
private String app_id;
@ -71,30 +71,31 @@ public class CrypConfigureServiceImpl extends BaseServiceImpl<CrypConfigureMappe
/**
* 调用天擎接口
*
* @param bean
* @return
*/
@Override
@Async
public Boolean callUniInterface(CrypBean bean){
log.info("区块链------callUniInterface---入参-----"+JSON.toJSONString(bean));
public Boolean callUniInterface(CrypBean bean) {
log.info("区块链------callUniInterface---入参-----" + JSON.toJSONString(bean));
BlockChainLog blockChainLog = new BlockChainLog();
blockChainLog.setId(PropertyUtils.getSnowflakeId());
//天擎地址
if(app_secret.equals("1mb6n6635cJkDb3pEQPUFXc2nRJ8RPaS")){
if ("1mb6n6635cJkDb3pEQPUFXc2nRJ8RPaS".equals(app_secret)) {
//测试环境
bean.setUrl(bean.getUrl().replace(app_url,app_url_test));
PEM_PATH = "admin_certPrivateNew.pem";
bean.setUrl(bean.getUrl().replace(app_url, app_url_test));
PEM_PATH = "admin_certPrivateNew.pem";
CRT_PATH = "adminNew.crt";
}else{
PEM_PATH = "bidding_certPrivate.pem";
} else {
PEM_PATH = "bidding_certPrivate.pem";
CRT_PATH = "bidding.crt";
//生产环境
bean.setUrl(bean.getUrl().replace(app_url_test,app_url));
bean.setUrl(bean.getUrl().replace(app_url_test, app_url));
}
log.info("加密文件:"+PEM_PATH);
log.info("解密文件:"+CRT_PATH);
log.info("请求路径:"+bean.getUrl());
log.info("加密文件:" + PEM_PATH);
log.info("解密文件:" + CRT_PATH);
log.info("请求路径:" + bean.getUrl());
blockChainLog.setInterfaceUrl(bean.getUrl());
try {
@ -105,20 +106,20 @@ public class CrypConfigureServiceImpl extends BaseServiceImpl<CrypConfigureMappe
map.put("SIGN", sign);
String json = getUniBss(bean.getReqName(),map);
String json = getUniBss(bean.getReqName(), map);
blockChainLog.setParam(json);//请求参数
String str = UniBssServiceImpl.uniBssHttpPost(bean.getUrl(), json);
blockChainLog.setResult(str);//返回参数
UniBss uniBssRsp = JSONArray.parseObject(str, UniBss.class);
if (uniBssRsp != null && UniBssConstant.RESP_CODE_00000.equals(uniBssRsp.getUniBssHead().getRespCode())) {
System.out.println("返回接口:"+uniBssRsp);
System.out.println("返回接口:" + uniBssRsp);
if(str!=null&&!"".equals(str)&&str.indexOf("_RSP\":{\"Code\":200,")>=0){
if (str != null && !"".equals(str) && str.indexOf("_RSP\":{\"Code\":200,") >= 0) {
blockChainLog.setStatus(0);//成功
this.iBlockChainLogService.save(blockChainLog);
return true;
}else{
} else {
blockChainLog.setStatus(1);//失败
}
} else {
@ -128,7 +129,7 @@ public class CrypConfigureServiceImpl extends BaseServiceImpl<CrypConfigureMappe
"(" + UniBssConstant.getRESP_CODE_Map(uniBssRsp.getUniBssHead().getRespCode()) + ")。" +
"RESP_DESC:" + uniBssRsp.getUniBssHead().getRespDesc(), bean);
}
}catch (Exception e){
} catch (Exception e) {
blockChainLog.setStatus(1);
blockChainLog.setResult(e.getMessage());
}
@ -140,60 +141,61 @@ public class CrypConfigureServiceImpl extends BaseServiceImpl<CrypConfigureMappe
/**
* 加载失败日志再发送
*
* @param
* @return
*/
@Override
public Boolean errorLogsGoToCryp(BlockChainLogVo vo){
log.info("区块链------callUniInterface---入参-----"+JSON.toJSONString(vo));
if(vo.getStatus()==null||"".equals(vo.getStatus())){
public Boolean errorLogsGoToCryp(BlockChainLogVo vo) {
log.info("区块链------callUniInterface---入参-----" + JSON.toJSONString(vo));
if (vo.getStatus() == null || "".equals(vo.getStatus())) {
vo.setStatus(1);//默认失败
}
SimpleDateFormat dateFormate = new SimpleDateFormat("yyyy-MM-dd");
String date = dateFormate.format(new Date());
if(vo.getStartTime()==null||"".equals(vo.getStartTime())){
vo.setStartTime(date+" 00:00:00");//默认当天00000
if (vo.getStartTime() == null || "".equals(vo.getStartTime())) {
vo.setStartTime(date + " 00:00:00");//默认当天00000
}
if(vo.getEndTime()==null||"".equals(vo.getEndTime())){
vo.setEndTime(date+" 23:59:59");//默认当天235959
if (vo.getEndTime() == null || "".equals(vo.getEndTime())) {
vo.setEndTime(date + " 23:59:59");//默认当天235959
}
BlockChainLog blog = BeanUtil.toBean(vo,BlockChainLog.class);
BlockChainLog blog = BeanUtil.toBean(vo, BlockChainLog.class);
LambdaQueryWrapper<BlockChainLog> query = Wrappers.lambdaQuery(blog);
//状态
if(vo.getStatus()!=null&&!"".equals(vo.getStatus())){
query.eq(BlockChainLog::getStatus,vo.getStatus());
if (vo.getStatus() != null && !"".equals(vo.getStatus())) {
query.eq(BlockChainLog::getStatus, vo.getStatus());
}
//时间
if(vo.getStartTime()!=null&&!"".equals(vo.getStartTime())){
query.ge(BlockChainLog::getCreateDate,vo.getStartTime());
if (vo.getStartTime() != null && !"".equals(vo.getStartTime())) {
query.ge(BlockChainLog::getCreateDate, vo.getStartTime());
}
if(vo.getEndTime()!=null&&!"".equals(vo.getEndTime())){
query.le(BlockChainLog::getCreateDate,vo.getEndTime());
if (vo.getEndTime() != null && !"".equals(vo.getEndTime())) {
query.le(BlockChainLog::getCreateDate, vo.getEndTime());
}
List<BlockChainLog> logList = this.iBlockChainLogService.list(query);
logList.forEach(blockChainLog->{
log.info("请求路径:"+blockChainLog.getInterfaceUrl());
logList.forEach(blockChainLog -> {
log.info("请求路径:" + blockChainLog.getInterfaceUrl());
try {
String json = blockChainLog.getParam();
String json = blockChainLog.getParam();
//blockChainLog.setParam(json);//请求参数
String str = UniBssServiceImpl.uniBssHttpPost(blockChainLog.getInterfaceUrl(), json);
blockChainLog.setResult(str);//返回参数
UniBss uniBssRsp = JSONArray.parseObject(str, UniBss.class);
if (uniBssRsp != null && UniBssConstant.RESP_CODE_00000.equals(uniBssRsp.getUniBssHead().getRespCode())) {
System.out.println("返回接口:"+uniBssRsp);
System.out.println("返回接口:" + uniBssRsp);
if(str!=null&&!"".equals(str)&&str.indexOf("_RSP\":{\"Code\":200,")>=0){
if (str != null && !"".equals(str) && str.indexOf("_RSP\":{\"Code\":200,") >= 0) {
blockChainLog.setStatus(0);//成功
this.iBlockChainLogService.saveOrUpdate(blockChainLog);
}else{
} else {
blockChainLog.setStatus(1);//失败
}
} else {
@ -203,7 +205,7 @@ public class CrypConfigureServiceImpl extends BaseServiceImpl<CrypConfigureMappe
"(" + UniBssConstant.getRESP_CODE_Map(uniBssRsp.getUniBssHead().getRespCode()) + ")。" +
"RESP_DESC:" + uniBssRsp.getUniBssHead().getRespDesc());
}
}catch (Exception e){
} catch (Exception e) {
blockChainLog.setStatus(1);
blockChainLog.setResult(e.getMessage());
}
@ -215,13 +217,14 @@ public class CrypConfigureServiceImpl extends BaseServiceImpl<CrypConfigureMappe
/**
* 加密
*
* @param object
* @return
*/
@Override
public CrypBean signObject(Object object){
public CrypBean signObject(Object object) {
CrypBean bean = new CrypBean();
try{
try {
bean.setObject(object);
String signValue = getSignValue(bean.getObject());
@ -229,8 +232,8 @@ public class CrypConfigureServiceImpl extends BaseServiceImpl<CrypConfigureMappe
bean.setSign(signValue);
return bean;
}catch (Exception e){
log.error("加密异常:"+e);
} catch (Exception e) {
log.error("加密异常:" + e);
}
return bean;
@ -238,132 +241,137 @@ public class CrypConfigureServiceImpl extends BaseServiceImpl<CrypConfigureMappe
/**
* 获取加密签名
*
* @param object
* @return
*/
private String getSignValue(Object object){
private String getSignValue(Object object) {
String signValue = "";
try{
try {
log.info("加密参数1:"+object);
log.info("加密参数1:" + object);
String json = JSONArray.toJSONString(object);
Map<String,Object> jsonMap = JSONArray.parseObject(json);
Map<String, Object> jsonMap = JSONArray.parseObject(json);
Object signObject = new Object();
if(jsonMap.get("BODY_LIST")!=null){
List jsonList = (List)jsonMap.get("BODY_LIST");
log.info("加密参数2:"+jsonList);
if (jsonMap.get("BODY_LIST") != null) {
List jsonList = (List) jsonMap.get("BODY_LIST");
log.info("加密参数2:" + jsonList);
InputStream is = CrypConfigureServiceImpl.class.getClassLoader().getResourceAsStream(PEM_PATH);
signValue = CrypServiceImpl.signObject2(jsonList,IOUtils.toString(is));
}else{
log.info("加密参数2:"+jsonMap);
signValue = CrypServiceImpl.signObject2(jsonList, IOUtils.toString(is));
} else {
log.info("加密参数2:" + jsonMap);
InputStream is = CrypConfigureServiceImpl.class.getClassLoader().getResourceAsStream(PEM_PATH);
signValue = CrypServiceImpl.signObject2(jsonMap,IOUtils.toString(is));
signValue = CrypServiceImpl.signObject2(jsonMap, IOUtils.toString(is));
}
log.info("加密结果:"+signValue);
}catch (Exception e){
log.info("---------加密异常-"+e.getMessage());
log.info("加密结果:" + signValue);
} catch (Exception e) {
log.info("---------加密异常-" + e.getMessage());
}
return signValue;
}
/**
* 获取加密签名
*
* @param map
* @return
*/
private String getUniBss(String reqName, Map<String,Object> map){
private String getUniBss(String reqName, Map<String, Object> map) {
UniBss uniBss = new UniBss();
uniBss.setUniBssAttached(new UniBssAttached().setMediaInf(""));
//天擎部分head
UniBssUtil util = new UniBssUtil(app_id,app_secret);
UniBssUtil util = new UniBssUtil(app_id, app_secret);
uniBss.setUniBssHead(util.getUniBssHead());
UniReqHead reqhead = new UniReqHead();
//测试写死
String accessToken = "MQjkzVoYoSHe6r/3uZm0MV/TLx+n8PS9ivfPhgY4bWmh+8DVxj7vTC15xbBkuV8oujD3XBZPP7PhcWag9UU5IzsUBT7PSwPhqi/fUqa+iAWhCWpvyihG/23BAY3rJyaoa3OdMNSnIh8woPDCJQTzCTpNtg0toKwdWnuc2mig7vI0Lm9lePvrx3XxFLSaFr+jB5C3qnAX4uUBioZzithSjtra1QUK6S1cb9DCmpj6NRI=";
//SystemId测试环境 990001 生产环境 74
if(app_secret.equals("1mb6n6635cJkDb3pEQPUFXc2nRJ8RPaS")){
if ("1mb6n6635cJkDb3pEQPUFXc2nRJ8RPaS".equals(app_secret)) {
//测试环境
reqhead.setSystemId("990001");
}else{
} else {
//生产环境
reqhead.setSystemId("74");
accessToken = AccessToken.tokenCreate("bidding");
accessToken = accessToken.replaceAll("\n","");
log.info("获取token:"+accessToken);
accessToken = accessToken.replaceAll("\n", "");
log.info("获取token:" + accessToken);
}
reqhead.setSystemName("bidding");
reqhead.setUserId(service.getCacheUser().getUserId()!=null?service.getCacheUser().getUserId():"dzztb");
reqhead.setUserName(service.getCacheUser().getUserId()!=null?service.getCacheUser().getUserId():"dzztb");
reqhead.setUserId(service.getCacheUser().getUserId() != null ? service.getCacheUser().getUserId() : "dzztb");
reqhead.setUserName(service.getCacheUser().getUserId() != null ? service.getCacheUser().getUserId() : "dzztb");
reqhead.setAccessToken(accessToken);
log.info("业务参数封装前:"+map);
log.info("业务参数封装前:" + map);
UniCrpyReq req = new UniCrpyReq();
req.setBody(map);
req.setHead(reqhead);
log.info("业务参数封装中:"+req);;
log.info("业务参数封装中:" + req);
;
Map reqMap = new HashMap();
reqMap.put(reqName,req);
reqMap.put(reqName, req);
uniBss.setUniBssBodyMap(reqMap);
log.info("业务参数封装后:"+reqMap);
log.info("业务参数封装后uniBss"+uniBss);
log.info("业务参数封装后:" + reqMap);
log.info("业务参数封装后uniBss" + uniBss);
return JSON.toJSONString(uniBss);
}
/**
* 解密
*
* @param bean
* @return
*/
@Override
public Boolean verifyObject(CrypBean bean){
public Boolean verifyObject(CrypBean bean) {
try{
try {
log.info("解密参数1:" + bean);
String json = JSONArray.toJSONString(bean.getObject());
Map<String, Object> jsonMap = JSONArray.parseObject(json, Map.class);
if(jsonMap.get("BODY_LIST")!=null){
List jsonList = (List)jsonMap.get("BODY_LIST");
log.info("解密参数2:"+jsonList);
if (jsonMap.get("BODY_LIST") != null) {
List jsonList = (List) jsonMap.get("BODY_LIST");
log.info("解密参数2:" + jsonList);
InputStream is = CrypConfigureServiceImpl.class.getClassLoader().getResourceAsStream(CRT_PATH);
Boolean b = CrypServiceImpl.verifyValue(bean.getSign(), jsonList, IOUtils.toString(is));
return b;
}else {
} else {
log.info("解密参数2:" + bean);
InputStream is = CrypConfigureServiceImpl.class.getClassLoader().getResourceAsStream(CRT_PATH);
Boolean b = CrypServiceImpl.verifyValue(bean.getSign(), jsonMap, IOUtils.toString(is));
return b;
}
}catch (Exception e){
log.info("-----------解密失败"+e.getMessage());
} catch (Exception e) {
log.info("-----------解密失败" + e.getMessage());
}
return false;
}
public static Map<String,Object> parseJSON2Map(String jsonStr){
Map<String,Object> map = new HashMap<String,Object>();
Map strmap = JSONArray.parseObject(jsonStr,Map.class);
for(Object k : strmap.keySet()){
public static Map<String, Object> parseJSON2Map(String jsonStr) {
Map<String, Object> map = new HashMap<String, Object>();
Map strmap = JSONArray.parseObject(jsonStr, Map.class);
for (Object k : strmap.keySet()) {
Object v = strmap.get(k);
if(v instanceof JSONArray){
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
Iterator it = ((JSONArray)v).iterator();
while (it.hasNext()){
if (v instanceof JSONArray) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Iterator it = ((JSONArray) v).iterator();
while (it.hasNext()) {
Object json2 = it.next();
list.add(parseJSON2Map(json2.toString()));
}
map.put(k.toString(),list);
}else{
map.put(k.toString(),v);
map.put(k.toString(), list);
} else {
map.put(k.toString(), v);
}
}
return map;
@ -413,6 +421,5 @@ public class CrypConfigureServiceImpl extends BaseServiceImpl<CrypConfigureMappe
// System.out.println("verify result of Map: "+ isOk);
}
}

View File

@ -1,11 +1,11 @@
package com.chinaunicom.mall.ebtp.extend.feign.config;
import com.alibaba.fastjson.JSONObject;
import com.chinaunicom.mall.ebtp.extend.feign.utils.UrlConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
@ -22,6 +22,9 @@ import java.net.URL;
@Configuration
public class FeignConfiguration implements RequestInterceptor {
@Value("${document.clientHttpUrl}")
private String clientHttpUrl;
@Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
@ -42,10 +45,10 @@ public class FeignConfiguration implements RequestInterceptor {
}
}
public static String getAccessToken() {
private String getAccessToken() {
StringBuffer strBf = new StringBuffer();
try {
URL realUrl = new URL(UrlConstants.clientHttpUrl);
URL realUrl = new URL(clientHttpUrl);
//将realUrl以 open方法返回的urlConnection 连接强转为HttpURLConnection连接 (标识一个url所引用的远程对象连接)
HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();// 此时cnnection只是为一个连接对象,待连接中
//设置连接输出流为true,默认false (post请求是以流的方式隐式的传递参数)

View File

@ -1,17 +1,13 @@
package com.chinaunicom.mall.ebtp.extend.feign.utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "document")
//@Component
//@ConfigurationProperties(prefix = "document")
public class UrlConstants {
public static String clientHttpUrl;
@Value("${document.clientHttpUrl}")
public void setClientHttpUrl(String confPath) {
clientHttpUrl = confPath;
}
// public static String clientHttpUrl;
//
// @Value("${document.clientHttpUrl}")
// public void setClientHttpUrl(String confPath) {
// clientHttpUrl = confPath;
// }
}

View File

@ -5,6 +5,7 @@ import cn.com.jit.tsa.client.TSAClient;
import cn.com.jit.tsa.client.TSAClientFactory;
import cn.com.jit.tsa.client.TSASignedResult;
import cn.com.jit.tsa.client.TSAVerifyResult;
import cn.hutool.core.exceptions.ExceptionUtil;
import com.chinaunicom.mall.ebtp.extend.timeService.tsa.SystemTime;
import com.chinaunicom.mall.ebtp.extend.timeService.tsa.TtsAgent;
import lombok.extern.slf4j.Slf4j;
@ -22,16 +23,16 @@ import java.util.Properties;
@Service
public class TimeServiceConstant {
public static TSAClient client;
private static TSAClient client;
@Value("${spring.redis.sentinel.master}")
private String redis;
static {
try{
try {
Properties prop = new Properties();
ClassPathResource classPathResource = new ClassPathResource("cssconfig.properties");
InputStream inputStream =classPathResource.getInputStream();
InputStream inputStream = classPathResource.getInputStream();
prop.load(inputStream);
inputStream.close();
@ -39,67 +40,71 @@ public class TimeServiceConstant {
TSAClientFactory factory = TSAClientFactory.newInstance(prop);
// 获得TSAClient
client = (TSAClient) factory.getTSAClient();
}catch (Exception e){
} catch (Exception e) {
log.error("读取配置文件或连接时间戳服务器异常", e);
}
}
/**
* 申请时间戳
*
* @param data 待申请时间戳的原文
* @return 时间戳加密原文
*/
public String signTimeStamp(String data){
if(redis.equals("eshop-redis-sim")){
public String signTimeStamp(String data) {
if ("eshop-redis-sim".equals(redis)) {
return "";
}
try{
try {
data = data!=null&&!"".equals(data)?data:"system";
data = data != null && !"".equals(data) ? data : "system";
//第三步:申请时间戳,向时间戳服务器发起申请时间戳请求,返回时间戳结果
TSASignedResult result = client.signTimeStamp("SHA1", data.getBytes("UTF-8"));
//第四步:获取时间戳数据,tsaData为时间戳数据,验证时间戳时使用,如果不是实时验证,需要将时间戳数据保存在应用服务器
byte[] tsaData = result.getSignedData();
log.info("tsaData -->"+tsaData);
log.info("tsaData -->" + tsaData);
String timestamp = Base64.encodeBase64String(tsaData);
log.info("timestamp -->"+timestamp);
log.info("timestamp -->" + timestamp);
return timestamp;
}catch (Exception e){
} catch (Exception e) {
log.error("申请时间戳异常", e);
}
return "";
}
/**
* 解析时间戳
*
* @param timestamp 时间戳加密原文
* @return 时间戳对象
*/
public TtsAgent.TtsParseResult verifyTimeStamp2(String timestamp){
public TtsAgent.TtsParseResult verifyTimeStamp2(String timestamp) {
String systemtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
TtsAgent.TtsParseResult ttsParseResult = new TtsAgent.TtsParseResult(systemtime,"","");
if(redis.equals("eshop-redis-sim")){
TtsAgent.TtsParseResult ttsParseResult = new TtsAgent.TtsParseResult(systemtime, "", "");
if ("eshop-redis-sim".equals(redis)) {
return ttsParseResult;
}
try{
try {
log.info("timestamp -->"+timestamp);
log.info("timestamp -->" + timestamp);
TSAVerifyResult verifyResult = this.verifyTimeStamp(timestamp);
String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(verifyResult.getSignedTime());
ttsParseResult = new TtsAgent.TtsParseResult(time, HelperUtil.bytesToHexString(verifyResult.getData()),
verifyResult.getSignerSubject());
}catch (Exception e){
} catch (Exception e) {
log.error("解析时间戳", e);
}
return ttsParseResult;
}
private TSAVerifyResult verifyTimeStamp(String timestamp){
private TSAVerifyResult verifyTimeStamp(String timestamp) {
try{
try {
log.info("timestamp -->"+timestamp);
log.info("timestamp -->" + timestamp);
TSAVerifyResult verifyResult = client.verifyTimeStamp(Base64.decodeBase64(timestamp));
return verifyResult;
}catch (Exception e){
} catch (Exception e) {
log.error("解析时间戳", e);
}
return null;
@ -107,20 +112,21 @@ public class TimeServiceConstant {
/**
* 获取时间戳
*
* @param data 待申请时间戳的原文
* @return 时间戳对象
*/
public TtsAgent.TtsParseResult getServiceTimeObj(String data){
public TtsAgent.TtsParseResult getServiceTimeObj(String data) {
String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
TtsAgent.TtsParseResult ttsParseResult = new TtsAgent.TtsParseResult(time,"","");
if(redis.equals("eshop-redis-sim")){
TtsAgent.TtsParseResult ttsParseResult = new TtsAgent.TtsParseResult(time, "", "");
if ("eshop-redis-sim".equals(redis)) {
return ttsParseResult;
}
try{
try {
String timestamp = this.signTimeStamp(data);
ttsParseResult = this.verifyTimeStamp2(timestamp);
}catch (Exception e){
} catch (Exception e) {
log.error("获取时间戳异常", e);
}
return ttsParseResult;
@ -128,21 +134,22 @@ public class TimeServiceConstant {
/**
* 直接获取获取时间戳 时间1
*
* @param data 待申请时间戳的原文
* @return 时间
*/
public String getServiceTime(String data){
log.info("------------------redis-"+redis);
public String getServiceTime(String data) {
log.info("------------------redis-" + redis);
String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
if(redis.equals("eshop-redis-sim")){
if ("eshop-redis-sim".equals(redis)) {
return time;
}
try{
try {
String timestamp = this.signTimeStamp(data);
TSAVerifyResult verifyResult = this.verifyTimeStamp(timestamp);
time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(verifyResult.getSignedTime());
}catch (Exception e){
} catch (Exception e) {
log.error("获取时间戳异常", e);
}
return time;
@ -151,53 +158,56 @@ public class TimeServiceConstant {
/**
* 直接获取获取时间戳 时间1
*
* @param data 待申请时间戳的原文
* @return date时间
*/
public Date getServiceDate(String data){
if(redis.equals("eshop-redis-sim")){
public Date getServiceDate(String data) {
if ("eshop-redis-sim".equals(redis)) {
return new Date();
}
try{
try {
String timestamp = this.signTimeStamp(data);
TSAVerifyResult verifyResult = this.verifyTimeStamp(timestamp);
Date date = verifyResult.getSignedTime();
return date;
}catch (Exception e){
} catch (Exception e) {
log.error("获取时间戳异常", e);
}
return new Date();
}
/**
* 获取年月日时分秒分割存储对象
*
* @param data 待申请时间戳的原文
* @return SystemTime
*/
public SystemTime getServiceSystemTime(String data){
public SystemTime getServiceSystemTime(String data) {
Date date = new Date();
if(redis.equals("eshop-redis-sim")){
if ("eshop-redis-sim".equals(redis)) {
return new SystemTime()
.setYear(date.getYear()+1900)
.setMonth(date.getMonth()+1)
.setYear(date.getYear() + 1900)
.setMonth(date.getMonth() + 1)
.setDate(date.getDate())
.setHour(date.getHours())
.setMinute(date.getMinutes())
.setSecond(date.getSeconds())
.setTimestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
}
try{
try {
String timestamp = this.signTimeStamp(data);
TSAVerifyResult verifyResult = this.verifyTimeStamp(timestamp);
date = verifyResult.getSignedTime();
}catch (Exception e){
} catch (Exception e) {
log.error("获取时间戳异常", e);
}
SystemTime systemTime = new SystemTime()
.setYear(date.getYear()+1900)
.setMonth(date.getMonth()+1)
.setYear(date.getYear() + 1900)
.setMonth(date.getMonth() + 1)
.setDate(date.getDate())
.setHour(date.getHours())
.setMinute(date.getMinutes())
@ -206,19 +216,19 @@ public class TimeServiceConstant {
return systemTime;
}
public static void main(String arge[]){
try{
public static void main(String arge[]) {
try {
Date date = new Date();
System.out.println("-----------"+(date.getYear()+1900));
System.out.println("-----------"+(date.getMonth()+1));
System.out.println("-----------"+date.getDate());
System.out.println("-----------"+date.getHours());
System.out.println("-----------"+date.getMinutes());
System.out.println("-----------"+date.getSeconds());
System.out.println("-----------" + (date.getYear() + 1900));
System.out.println("-----------" + (date.getMonth() + 1));
System.out.println("-----------" + date.getDate());
System.out.println("-----------" + date.getHours());
System.out.println("-----------" + date.getMinutes());
System.out.println("-----------" + date.getSeconds());
}catch (Exception e){
e.printStackTrace();
} catch (Exception e) {
log.info(ExceptionUtil.stacktraceToString(e));
}
}
}

View File

@ -1,13 +1,14 @@
package com.chinaunicom.mall.ebtp.extend.timeService.controller;
import cn.hutool.core.exceptions.ExceptionUtil;
import com.chinaunicom.mall.ebtp.common.base.entity.BaseResponse;
import com.chinaunicom.mall.ebtp.extend.export.service.ExportServiceFactory;
import com.chinaunicom.mall.ebtp.extend.timeService.TimeServiceConstant;
import com.chinaunicom.mall.ebtp.extend.timeService.tsa.SystemTime;
import com.chinaunicom.mall.ebtp.extend.timeService.tsa.TtsAgent;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
@ -20,10 +21,12 @@ import java.util.Date;
@RestController
@Api(tags = "")
@RequestMapping("/v1/timeService")
@Slf4j
public class TimeServiceController {
@Autowired
private TimeServiceConstant timeServiceConstant;
/**
* 申请时间戳
*
@ -118,7 +121,7 @@ public class TimeServiceController {
.setSecond((int) s);
return BaseResponse.success(systemTime);
} catch (ParseException e) {
e.printStackTrace();
log.info(ExceptionUtil.stacktraceToString(e));
}
return BaseResponse.success(new SystemTime());
}