Commit ef14e210 by chengzhuoshen

commit init

parents
package com.prowidesoftware.brilliance.constants;
public class ERROR {
public static String ERROR_0001="ERROR_0001";
public static String ERROR_0001_DESC="xml转Obj失败,请联系技术人员!";
public static String ERROR_0002="ERROR_0002";
public static String ERROR_0002_DESC="swift模板转字符串失败,请检查";
public static String ERROR_0003="ERROR_0003";
public static String ERROR_0003_DESC="swift log config error";
}
package com.prowidesoftware.brilliance.constants;
public class Mx2MtConstants {
public static final String BICSUFFIX = "AXXX";
public static final String BICMIDDLE = "A";
public static final String DRCRMARK_C = "C";
public static final String DRCRMARK_D = "D";
public static final String DRCRMARK_RC = "RC";
public static final String DRCRMARK_RD = "RD";
/**
* 回车换行
*/
public static final String NEW_LINE = "\r\n";
public static final String MT_TYPE_900 = "900";
public static final String MT_TYPE_910 = "910";
public static final String MT_TYPE_940 = "940";
public static final String MT_TYPE_950 = "950";
public static final String MT_TYPE_103 = "103";
public static final String OUT_PUT_FILE_PATH = "outPutFilePath";
public static final String MX_OBJECT = "mxObj";
public static final String MT_TYPE = "mtType";
}
package com.prowidesoftware.brilliance.exception;
public class CommonRuntimeException extends RuntimeException {
static {
CommonRuntimeException.class.getName();
}
public CommonRuntimeException(String msg) {
super(msg);
}
public CommonRuntimeException(String msg, Throwable cause) {
super(msg, cause);
}
public String getMessage() {
return buildMessage(super.getMessage(), getCause());
}
public Throwable getRootCause() {
return getRootCause(this);
}
private String buildMessage(String message, Throwable cause) {
if (cause == null) {
return message;
}
StringBuilder sb = new StringBuilder(64);
if (message != null) {
sb.append(message).append("; ");
}
sb.append("nested exception is ").append(cause);
return sb.toString();
}
private Throwable getRootCause(Throwable original) {
if (original == null) {
return null;
}
Throwable rootCause = null;
Throwable cause = original.getCause();
while (cause != null && cause != rootCause) {
rootCause = cause;
cause = cause.getCause();
}
return rootCause;
}
}
package com.prowidesoftware.brilliance.exception;
public class IORuntimeException extends CommonRuntimeException {
public IORuntimeException(String msg) {
super(msg);
}
public IORuntimeException(String msg, Throwable cause) {
super(msg, cause);
}
}
\ No newline at end of file
package com.prowidesoftware.brilliance.exception;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
/**
* 接口实例化异常
*/
public class InstantiateException extends CommonRuntimeException {
private final Class<?> beanClass;
private final Constructor<?> constructor;
private final Method constructingMethod;
public InstantiateException(Constructor<?> constructor, String msg, Throwable cause) {
super("Failed to instantiate [" + constructor.getDeclaringClass().getName() + "]: " + msg, cause);
this.beanClass = constructor.getDeclaringClass();
this.constructor = constructor;
this.constructingMethod = null;
}
public InstantiateException(String beanClass, String msg, Throwable cause) {
super("Failed to instantiate [" + beanClass + "]: " + msg, cause);
this.beanClass = null;
this.constructor = null;
this.constructingMethod = null;
}
public InstantiateException(Class<?> beanClass, String msg) {
super("Failed to instantiate [" + beanClass.getName() + "]: " + msg);
this.beanClass = beanClass;
this.constructor = null;
this.constructingMethod = null;
}
public InstantiateException(Class<?> beanClass, String msg, Throwable cause) {
super("Failed to instantiate [" + beanClass.getName() + "]: " + msg, cause);
this.beanClass = beanClass;
this.constructor = null;
this.constructingMethod = null;
}
public Class<?> getBeanClass() {
return this.beanClass;
}
public Constructor<?> getConstructor() {
return this.constructor;
}
public Method getConstructingMethod() {
return constructingMethod;
}
}
package com.prowidesoftware.brilliance.exception;
/**
* 接口通用异常类
*
* @author xiaoyuanzhen
*/
public class SwiftException
extends RuntimeException {
private String id;
private String message;
private Exception exception;
private static final long serialVersionUID = 1L;
public SwiftException(String id) {
super();
this.id = id;
}
public SwiftException(String id, String message) {
super();
this.id = id;
this.message = message;
}
public SwiftException(String id, Exception e) {
super();
this.id = id;
this.exception = e;
}
public SwiftException(String id, String message, Exception e) {
super();
this.id = id;
this.message = message;
this.exception = e;
}
public String getId() {
return id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Throwable getCause() {
return exception;
}
public Exception getException() {
return exception;
}
}
package com.prowidesoftware.brilliance.mx2mt;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.util.DateUtil;
import com.prowidesoftware.brilliance.util.StringUtil;
import com.prowidesoftware.swift.model.mx.dic.GroupHeader42;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
public abstract class AbstractMx2MtCreator implements Mx2MtCreator {
private static final Logger logger = LoggerFactory.getLogger(AbstractMx2MtCreator.class);
protected Map<String, Object> map = new HashMap<>();
protected AbstractMx2MtCreator withObj(Object obj) {
map.put(Mx2MtConstants.MX_OBJECT, obj);
return this;
}
protected AbstractMx2MtCreator withOutPutFilePath(String outPutFilePath) {
if (!StringUtil.isEmpty(outPutFilePath)) {
map.put(Mx2MtConstants.OUT_PUT_FILE_PATH, outPutFilePath);
}
return this;
}
protected AbstractMx2MtCreator withExtraMap(Map<String, Object> extraMap) {
if (extraMap != null && extraMap.size() > 0) {
logger.info("External Map...");
extraMap.forEach((key, value) -> {
logger.info(key + "-" + value);
map.put(key, value);
});
}
return this;
}
protected void generateCommonField(GroupHeader42 grpHdr) {
if (grpHdr != null) {
String createDateStr = DateUtil.format(grpHdr.getCreDtTm(), "YYMMdd");
String createTimeStr = DateUtil.format(grpHdr.getCreDtTm(), "HHmm");
map.put("createDate", createDateStr);
map.put("createTime", createTimeStr);
String outDateStr = DateUtil.formatNow( "YYMMdd");
String outTimeStr = DateUtil.formatNow("HHmm");
map.put("outDate", outDateStr);
map.put("outTime", outTimeStr);
}
}
public Map<String, Object> getMap() {
return map;
}
public void setMap(Map<String, Object> map) {
this.map = map;
}
}
package com.prowidesoftware.brilliance.mx2mt;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.util.StringUtil;
import java.util.Map;
public abstract class AbstractMx2MtFieldsGenerate implements Mx2MtFieldsGenerate {
protected Map<String, Object> map = null;
protected void withMap(Map<String, Object> targetMap) {
map = targetMap;
}
/**
* length == 8 append AXXX
* length == 11 substring(0,8)+A+substring(8)
* @param bicCode
* @return
*/
protected String processBicCode(String bicCode) {
String processedBicCode = "";
if (!StringUtil.isEmpty(bicCode)) {
if (bicCode.length() == 8) {
processedBicCode = bicCode + Mx2MtConstants.BICSUFFIX;
} else if (bicCode.length() == 11) {
processedBicCode = bicCode.substring(0, 8) + Mx2MtConstants.BICMIDDLE + bicCode.substring(8);
} else {
throw new SwiftException("ERROR", "BicCode length is invalid.");
}
}
return processedBicCode;
}
}
package com.prowidesoftware.brilliance.mx2mt;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.mx2mt.mt900910.Mx2Mt900910Creator;
import com.prowidesoftware.swift.model.mx.AbstractMX;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.List;
import java.util.Map;
public class Mx2MtCreateManager {
private static final Logger logger = LoggerFactory.getLogger(Mx2MtCreateManager.class);
private String msgType = "";
private Object mxObj = null;
public String getMsgType() {
return msgType;
}
public void setMsgType(String msgType) {
this.msgType = msgType;
}
public Object getMxObj() {
return mxObj;
}
public void setMxObj(Object mxObj) {
this.mxObj = mxObj;
}
public void init(String xmlStr) {
AbstractMX abstractMX = AbstractMX.parse(xmlStr);
msgType = (abstractMX.getMxId().getBusinessProcess().name()
+ abstractMX.getMxId().getFunctionality()
+ abstractMX.getMxId().getVariant()
+ abstractMX.getMxId().getVersion())
.trim()
.replace(".", "");
mxObj = abstractMX;
}
public String mx2mt(File file, String outPutFilePath, Map<String, Object> extraMap) throws Exception {
logger.info("invoke mx2mt(file) start...");
String xmlStr = FileUtils.readFileToString(file);
init(xmlStr);
logger.info("Xml Message Type = " + msgType);
logger.info("Xml Message Obj = " + mxObj);
return convert(outPutFilePath, extraMap);
}
public String mx2mt(File file, String outPutFilePath) throws Exception {
return mx2mt(file, outPutFilePath, null);
}
public String mx2mt(File file) throws Exception {
return mx2mt(file, null, null);
}
public String mx2mt(String xmlStr, String outPutFilePath, Map<String, Object> extraMap) throws Exception {
logger.info("invoke mx2mt(string) start...");
init(xmlStr);
logger.info("Xml Message Type = " + msgType);
logger.info("Xml Message Obj = " + mxObj);
return convert(outPutFilePath, extraMap);
}
public String mx2mt(String xmlStr, String outPutFilePath) throws Exception {
return mx2mt(xmlStr, outPutFilePath, null);
}
public String mx2mt(String xmlStr) throws Exception {
return mx2mt(xmlStr, null, null);
}
public String convert(String outPutFilePath, Map<String, Object> extraMap) throws SwiftException {
AbstractMx2MtCreator creator = getMx2MtCreator(msgType);
creator.withObj(mxObj).withOutPutFilePath(outPutFilePath).withExtraMap(extraMap);
List<Mx2MtFieldsGenerate> generateList = creator.getFieldsGenerateList();
for (int i=0; i<generateList.size(); i++) {
AbstractMx2MtFieldsGenerate fieldsGenerate = (AbstractMx2MtFieldsGenerate) generateList.get(i);
fieldsGenerate.withMap(creator.getMap());
fieldsGenerate.fieldsGenerate();
}
return creator.generateMtMsg();
}
public AbstractMx2MtCreator getMx2MtCreator(String msgType) throws SwiftException {
/*if ("pacs00800102".equals(msgType)) {
return new Mx2Mt103Creator();
} else if ("camt05300102".equals(msgType)) {
return new Mx2Mt950Creator();
} else*/ if ("camt05400102".equals(msgType)) {
return new Mx2Mt900910Creator();
} else {
throw new SwiftException("Invalid message type");
}
}
}
package com.prowidesoftware.brilliance.mx2mt;
import java.util.List;
public interface Mx2MtCreator {
public List<Mx2MtFieldsGenerate> getFieldsGenerateList();
public String generateMtMsg();
}
package com.prowidesoftware.brilliance.mx2mt;
import com.prowidesoftware.brilliance.exception.SwiftException;
public interface Mx2MtFieldsGenerate {
public void fieldsGenerate() throws SwiftException;
}
package com.prowidesoftware.brilliance.mx2mt.mt900910;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtCreator;
import com.prowidesoftware.brilliance.mx2mt.Mx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.mx2mt.mt900910.impl.*;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.util.StringUtil;
import com.prowidesoftware.brilliance.util.TemplateUtil;
import com.prowidesoftware.swift.model.mx.MxCamt05400102;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
public class Mx2Mt900910Creator extends AbstractMx2MtCreator {
private static final Logger logger = LoggerFactory.getLogger(Mx2Mt900910Creator.class);
@Override
public List<Mx2MtFieldsGenerate> getFieldsGenerateList() {
List<Mx2MtFieldsGenerate> fieldsGenerateList = new ArrayList<>();
fieldsGenerateList.add(new ReceiverBicFieldGenerate());
fieldsGenerateList.add(new SenderBicFieldGenerate());
fieldsGenerateList.add(new Field13DGenerate());
fieldsGenerateList.add(new Field20Generate());
fieldsGenerateList.add(new Field21Generate());
fieldsGenerateList.add(new Field25aGenerate());
fieldsGenerateList.add(new Field32AGenerate());
fieldsGenerateList.add(new Field50aGenerate());
fieldsGenerateList.add(new Field52aGenerate());
fieldsGenerateList.add(new Field56aGenerate());
fieldsGenerateList.add(new Field72Generate());
return fieldsGenerateList;
}
@Override
public String generateMtMsg() {
MxCamt05400102 mxCamt05400102 = (MxCamt05400102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05400102 != null
&& mxCamt05400102.getBkToCstmrDbtCdtNtfctn() != null
&& mxCamt05400102.getBkToCstmrDbtCdtNtfctn().getGrpHdr() != null) {
generateCommonField(mxCamt05400102.getBkToCstmrDbtCdtNtfctn().getGrpHdr());
}
validate();
map.forEach((key,value)->{
logger.info(key + "-" + value);
});
String outPutFilePath = (String)map.get(Mx2MtConstants.OUT_PUT_FILE_PATH);
String msg = TemplateUtil.makeFileByTemplate("swift_mt_900_910.vm", map, outPutFilePath, "utf-8");
return msg;
}
public void validate() {
String mtType = (String)map.get(Mx2MtConstants.MT_TYPE);
if (Mx2MtConstants.MT_TYPE_910.equals(mtType)) {
String field50a = (String)map.get("field50a");
String field52a = (String)map.get("field52a");
if (StringUtil.isEmpty(field50a) && StringUtil.isEmpty(field52a)) {
throw new SwiftException("ERROR", "Either field 50a or field 52a must be present.");
}
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt900910.impl;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.exception.SwiftException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Field13DGenerate extends AbstractMx2MtFieldsGenerate {
private static final Logger logger = LoggerFactory.getLogger(Field13DGenerate.class);
@Override
public void fieldsGenerate() throws SwiftException {
//no mapping
map.put("field13D", "");
}
}
package com.prowidesoftware.brilliance.mx2mt.mt900910.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.swift.model.mx.MxCamt05400102;
import com.prowidesoftware.swift.model.mx.dic.BankToCustomerDebitCreditNotificationV02;
import com.prowidesoftware.swift.model.mx.dic.GroupHeader42;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <GrpHdr><MsgId>
*/
public class Field20Generate extends AbstractMx2MtFieldsGenerate {
private static final Logger logger = LoggerFactory.getLogger(Field20Generate.class);
@Override
public void fieldsGenerate() throws SwiftException {
logger.info("Field20Generate start.");
try {
MxCamt05400102 mxCamt05400102 = (MxCamt05400102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05400102 == null || mxCamt05400102.getBkToCstmrDbtCdtNtfctn() == null) {
return;
}
BankToCustomerDebitCreditNotificationV02 bkToCstmrDbtCdtNtfctn = mxCamt05400102.getBkToCstmrDbtCdtNtfctn();
GroupHeader42 grpHdr = bkToCstmrDbtCdtNtfctn.getGrpHdr();
if (grpHdr != null) {
String field20 = grpHdr.getMsgId();
map.put("field20", field20);
}
} catch (Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT900/910 Field20 error");
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt900910.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.swift.model.mx.MxCamt05400102;
import com.prowidesoftware.swift.model.mx.dic.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* <Ntfctn><Ntry><NtryDtls><TxDtls><Refs><EndToEndId>
*/
public class Field21Generate extends AbstractMx2MtFieldsGenerate {
private static final Logger logger = LoggerFactory.getLogger(Field21Generate.class);
@Override
public void fieldsGenerate() throws SwiftException {
logger.info("Field21Generate start.");
try {
MxCamt05400102 mxCamt05400102 = (MxCamt05400102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05400102 == null || mxCamt05400102.getBkToCstmrDbtCdtNtfctn() == null) {
return;
}
BankToCustomerDebitCreditNotificationV02 bkToCstmrDbtCdtNtfctn = mxCamt05400102.getBkToCstmrDbtCdtNtfctn();
List<AccountNotification2> ntfctnList = bkToCstmrDbtCdtNtfctn.getNtfctn();
if (ntfctnList != null && ntfctnList.size() > 0) {
AccountNotification2 ntfctn = ntfctnList.get(0);
List<ReportEntry2> ntryList = ntfctn.getNtry();
if (ntryList != null && ntryList.size() > 0) {
ReportEntry2 ntry = ntryList.get(0);
List<EntryDetails1> ntryDtlsList = ntry.getNtryDtls();
if (ntryDtlsList != null && ntryDtlsList.size() > 0) {
EntryDetails1 ntryDtls = ntryDtlsList.get(0);
List<EntryTransaction2> txDtlsList = ntryDtls.getTxDtls();
if (txDtlsList != null && txDtlsList.size() > 0) {
EntryTransaction2 txDtls = txDtlsList.get(0);
TransactionReferences2 refs = txDtls.getRefs();
if (refs != null) {
map.put("field21", refs.getEndToEndId());
}
}
}
}
}
} catch (Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT900/910 Field21 error");
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt900910.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.util.StringUtil;
import com.prowidesoftware.swift.model.mx.MxCamt05400102;
import com.prowidesoftware.swift.model.mx.dic.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* <Ntfctn><Acct><Id><IBAN>
* <Ntfctn><Acct><Id><<Othr><Id>
*/
public class Field25aGenerate extends AbstractMx2MtFieldsGenerate {
private static final Logger logger = LoggerFactory.getLogger(Field25aGenerate.class);
@Override
public void fieldsGenerate() throws SwiftException {
logger.info("Field25aGenerate start.");
try {
MxCamt05400102 mxCamt05400102 = (MxCamt05400102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05400102 == null || mxCamt05400102.getBkToCstmrDbtCdtNtfctn() == null) {
return;
}
BankToCustomerDebitCreditNotificationV02 bkToCstmrDbtCdtNtfctn = mxCamt05400102.getBkToCstmrDbtCdtNtfctn();
List<AccountNotification2> ntfctnList = bkToCstmrDbtCdtNtfctn.getNtfctn();
if (ntfctnList != null && ntfctnList.size() > 0) {
AccountNotification2 ntfctn = ntfctnList.get(0);
CashAccount20 acct = ntfctn.getAcct();
if (acct != null) {
AccountIdentification4Choice id = acct.getId();
if (id != null) {
if (!StringUtil.isEmpty(id.getIBAN())) {
map.put("field25a", id.getIBAN());
} else {
GenericAccountIdentification1 othr = id.getOthr();
if (othr != null) {
map.put("field25a", othr.getId());
}
}
}
}
}
} catch (Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT900/910 Field25a error");
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt900910.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.util.DateUtil;
import com.prowidesoftware.brilliance.util.NumberUtil;
import com.prowidesoftware.swift.model.mx.MxCamt05400102;
import com.prowidesoftware.swift.model.mx.dic.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* <Ntfctn><Ntry><ValDt><Dt>
* <Ntfctn><Ntry><Amt Ccy="XXX">
*/
public class Field32AGenerate extends AbstractMx2MtFieldsGenerate {
private static final Logger logger = LoggerFactory.getLogger(Field32AGenerate.class);
@Override
public void fieldsGenerate() throws SwiftException {
logger.info("Field32AGenerate start.");
try {
MxCamt05400102 mxCamt05400102 = (MxCamt05400102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05400102 == null || mxCamt05400102.getBkToCstmrDbtCdtNtfctn() == null) {
return;
}
BankToCustomerDebitCreditNotificationV02 bkToCstmrDbtCdtNtfctn = mxCamt05400102.getBkToCstmrDbtCdtNtfctn();
List<AccountNotification2> ntfctnList = bkToCstmrDbtCdtNtfctn.getNtfctn();
if (ntfctnList != null && ntfctnList.size() > 0) {
AccountNotification2 ntfctn = ntfctnList.get(0);
List<ReportEntry2> ntryList = ntfctn.getNtry();
if (ntryList != null && ntryList.size() > 0) {
ReportEntry2 ntry = ntryList.get(0);
String dateStr = "";
if (ntry.getValDt() != null) {
dateStr = DateUtil.format(ntry.getValDt().getDt(), "YYMMdd");
}
String ccy = "";
String amtStr = "";
ActiveOrHistoricCurrencyAndAmount amt = ntry.getAmt();
if (amt != null) {
ccy = amt.getCcy();
amtStr = NumberUtil.formatAmt(amt.getValue(), ccy);
}
map.put("field32A", dateStr+ccy+amtStr);
//judge 900 or 910
if (CreditDebitCode.DBIT.equals(ntry.getCdtDbtInd())) {
map.put(Mx2MtConstants.MT_TYPE, Mx2MtConstants.MT_TYPE_900);
} else if (CreditDebitCode.CRDT.equals(ntry.getCdtDbtInd())) {
map.put(Mx2MtConstants.MT_TYPE, Mx2MtConstants.MT_TYPE_910);
}
}
}
} catch (Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT900/910 Field32A error");
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt900910.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.util.StringUtil;
import com.prowidesoftware.swift.model.mx.MxCamt05400102;
import com.prowidesoftware.swift.model.mx.dic.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* 50A
* <Ntfctn><Ntry><NtryDtls><TxDtls><RltdPties><Dbtr><Pty><Id><OrgId><AnyBIC>
* <Ntfctn><Ntry><NtryDtls><TxDtls><RltdPties><DbtrAcct><Id><IBAN>
* <Ntfctn><Ntry><NtryDtls><TxDtls><RltdPties><DbtrAcct><Id><Othr><Id>
*
* 50K
* <Ntfctn><Ntry><NtryDtls><TxDtls><RltdPties><Dbtr><Pty><Nm>
* <Ntfctn><Ntry><NtryDtls><TxDtls><RltdPties><Dbtr><Pty><PstlAdr><AdrLine>
*/
public class Field50aGenerate extends AbstractMx2MtFieldsGenerate {
private static final Logger logger = LoggerFactory.getLogger(Field50aGenerate.class);
@Override
public void fieldsGenerate() throws SwiftException {
String mtType = (String)map.get("mtType");
if (!Mx2MtConstants.MT_TYPE_910.equals(mtType)) {
return;
}
logger.info("Field50aGenerate start.");
try {
TransactionParty2 rltdPties = getTransactionParty2();
if (rltdPties == null) {
logger.info("<Ntfctn><Ntry><NtryDtls><TxDtls><RltdPties> Object is null.");
return;
}
String field50aOption = "";
String field50a = "";
PartyIdentification32 dbtr = rltdPties.getDbtr();
if (dbtr != null) {
if (dbtr.getId() != null
&& dbtr.getId().getOrgId() != null
&& !StringUtil.isEmpty(dbtr.getId().getOrgId().getBICOrBEI())) {
String bicCode = dbtr.getId().getOrgId().getBICOrBEI();
field50aOption = "A";
String iban = "";
String otherId = "";
CashAccount16 dbtrAcct = rltdPties.getDbtrAcct();
if (dbtrAcct.getId() != null) {
iban = dbtrAcct.getId().getIBAN();
if (StringUtil.isEmpty(iban)) {
GenericAccountIdentification1 othr = dbtrAcct.getId().getOthr();
if (othr != null) {
otherId = othr.getId();
}
}
}
if (!StringUtil.isEmpty(iban)) {
field50a = "/"+iban + "\r\n" + bicCode;
} else if (!StringUtil.isEmpty(otherId)) {
field50a = "//CH"+otherId + "\r\n" + bicCode;
} else {
field50a = bicCode;
}
} else if (!StringUtil.isEmpty(dbtr.getNm())) {
field50aOption = "K";
field50a = "/" + dbtr.getNm();
PostalAddress6 pstlAdr = dbtr.getPstlAdr();
if (pstlAdr != null) {
List<String> adrLineList = pstlAdr.getAdrLine();
if (adrLineList.size() > 0) {
for (int i=0; i<adrLineList.size(); i++) {
if (i == 4) {
break;
}
String adrLine = adrLineList.get(i);
if (adrLine.length() > 35) {
adrLine = adrLine.substring(0, 35);
}
field50a += Mx2MtConstants.NEW_LINE+adrLine;
}
}
}
}
}
if (StringUtil.isNotEmpty(field50aOption) && StringUtil.isNotEmpty(field50a)) {
map.put("field50aOption", field50aOption);
map.put("field50a", field50a);
}
} catch (Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT900/910 Field50a error");
}
}
private TransactionParty2 getTransactionParty2() {
try {
TransactionParty2 rltdPties = null;
MxCamt05400102 mxCamt05400102 = (MxCamt05400102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05400102 == null || mxCamt05400102.getBkToCstmrDbtCdtNtfctn() == null) {
return null;
}
BankToCustomerDebitCreditNotificationV02 bkToCstmrDbtCdtNtfctn = mxCamt05400102.getBkToCstmrDbtCdtNtfctn();
List<AccountNotification2> ntfctnList = bkToCstmrDbtCdtNtfctn.getNtfctn();
if (ntfctnList != null && ntfctnList.size() > 0) {
AccountNotification2 ntfctn = ntfctnList.get(0);
List<ReportEntry2> ntryList = ntfctn.getNtry();
if (ntryList != null && ntryList.size() > 0) {
ReportEntry2 ntry = ntryList.get(0);
List<EntryDetails1> ntryDtlsList = ntry.getNtryDtls();
if (ntryDtlsList != null && ntryDtlsList.size() > 0) {
EntryDetails1 ntryDtls = ntryDtlsList.get(0);
List<EntryTransaction2> txDtlsList = ntryDtls.getTxDtls();
if (txDtlsList != null && txDtlsList.size() > 0) {
EntryTransaction2 txDtls = txDtlsList.get(0);
rltdPties = txDtls.getRltdPties();
}
}
}
}
return rltdPties;
} catch (Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT900/910 Field50a error");
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt900910.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.util.StringUtil;
import com.prowidesoftware.swift.model.mx.MxCamt05400102;
import com.prowidesoftware.swift.model.mx.dic.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class Field52aGenerate extends AbstractMx2MtFieldsGenerate {
private static final Logger logger = LoggerFactory.getLogger(Field52aGenerate.class);
@Override
public void fieldsGenerate() throws SwiftException {
logger.info("Field52aGenerate start.");
try {
BranchAndFinancialInstitutionIdentification4 crDrTrAgt = getCrDrTrAgt();
if (crDrTrAgt == null) {
logger.info("<Ntfctn><Ntry><NtryDtls><TxDtls><RltdAgts><DbtrAgt>or<CdtrAgt> Object is null.");
return;
}
String field52aOption = "";
String field52a = "";
FinancialInstitutionIdentification7 finInstnId = crDrTrAgt.getFinInstnId();
if (finInstnId != null) {
String bicCode = finInstnId.getBIC();
if (StringUtil.isNotEmpty(bicCode)) {
field52aOption = "A";
String memberId = "";
ClearingSystemMemberIdentification2 clrSysMmbId = finInstnId.getClrSysMmbId();
if (clrSysMmbId != null) {
memberId = clrSysMmbId.getMmbId();
}
if (StringUtil.isNotEmpty(memberId)) {
field52a = "/" + memberId + Mx2MtConstants.NEW_LINE + bicCode;
} else {
field52a = bicCode;
}
} else if (!StringUtil.isEmpty(finInstnId.getNm())){
field52aOption = "D";
field52a = "/" + finInstnId.getNm();
PostalAddress6 pstlAdr = finInstnId.getPstlAdr();
if (pstlAdr != null) {
List<String> adrLineList = pstlAdr.getAdrLine();
if (adrLineList.size() > 0) {
for (int i=0; i<adrLineList.size(); i++) {
if (i == 4) {
break;
}
String adrLine = adrLineList.get(i);
if (adrLine.length() > 35) {
adrLine = adrLine.substring(0, 35);
}
if (i==0 && StringUtil.isEmpty(field52a)) {
field52a += adrLine;
} else {
field52a += Mx2MtConstants.NEW_LINE+adrLine;
}
}
}
}
}
}
if (StringUtil.isNotEmpty(field52aOption) && StringUtil.isNotEmpty(field52a)) {
map.put("field52aOption", field52aOption);
map.put("field52a", field52a);
}
} catch (Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT900/910 Field52a error");
}
}
private BranchAndFinancialInstitutionIdentification4 getCrDrTrAgt() {
try {
BranchAndFinancialInstitutionIdentification4 crDrTrAgt = null;
MxCamt05400102 mxCamt05400102 = (MxCamt05400102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05400102 == null || mxCamt05400102.getBkToCstmrDbtCdtNtfctn() == null) {
return null;
}
BankToCustomerDebitCreditNotificationV02 bkToCstmrDbtCdtNtfctn = mxCamt05400102.getBkToCstmrDbtCdtNtfctn();
List<AccountNotification2> ntfctnList = bkToCstmrDbtCdtNtfctn.getNtfctn();
if (ntfctnList != null && ntfctnList.size() > 0) {
AccountNotification2 ntfctn = ntfctnList.get(0);
List<ReportEntry2> ntryList = ntfctn.getNtry();
if (ntryList != null && ntryList.size() > 0) {
ReportEntry2 ntry = ntryList.get(0);
List<EntryDetails1> ntryDtlsList = ntry.getNtryDtls();
if (ntryDtlsList != null && ntryDtlsList.size() > 0) {
EntryDetails1 ntryDtls = ntryDtlsList.get(0);
List<EntryTransaction2> txDtlsList = ntryDtls.getTxDtls();
if (txDtlsList != null && txDtlsList.size() > 0) {
EntryTransaction2 txDtls = txDtlsList.get(0);
TransactionAgents2 rltdAgts = txDtls.getRltdAgts();
if (rltdAgts != null) {
/*String mtType = (String)map.get("mtType");
if (Mx2MtConstants.MT_TYPE_900.equals(mtType)) {
crDrTrAgt = rltdAgts.getDbtrAgt();
} else if (Mx2MtConstants.MT_TYPE_910.equals(mtType)) {
crDrTrAgt = rltdAgts.getCdtrAgt();
}*/
crDrTrAgt = rltdAgts.getDbtrAgt();
}
}
}
}
}
return crDrTrAgt;
} catch (Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT900/910 Field52a error");
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt900910.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.util.StringUtil;
import com.prowidesoftware.swift.model.mx.MxCamt05400102;
import com.prowidesoftware.swift.model.mx.dic.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class Field56aGenerate extends AbstractMx2MtFieldsGenerate {
private static final Logger logger = LoggerFactory.getLogger(Field56aGenerate.class);
@Override
public void fieldsGenerate() throws SwiftException {
String mtType = (String)map.get("mtType");
if (!Mx2MtConstants.MT_TYPE_910.equals(mtType)) {
return;
}
logger.info("Field56aGenerate start.");
try {
BranchAndFinancialInstitutionIdentification4 intrmyAgt1 = getIntrmyAgt1();
if (intrmyAgt1 == null) {
logger.info("<Ntfctn><Ntry><NtryDtls><TxDtls><RltdAgts><IntrmyAgt1> Object is null.");
return;
}
String field56aOption = "";
String field56a = "";
FinancialInstitutionIdentification7 finInstnId = intrmyAgt1.getFinInstnId();
if (finInstnId != null) {
String bicCode = finInstnId.getBIC();
if (StringUtil.isNotEmpty(bicCode)) {
field56aOption = "A";
String memberId = "";
ClearingSystemMemberIdentification2 clrSysMmbId = finInstnId.getClrSysMmbId();
if (clrSysMmbId != null) {
memberId = clrSysMmbId.getMmbId();
}
if (StringUtil.isNotEmpty(memberId)) {
field56a = "/" + memberId + Mx2MtConstants.NEW_LINE + bicCode;
} else {
field56a = bicCode;
}
} else if (!StringUtil.isEmpty(finInstnId.getNm())){
field56aOption = "D";
field56a = "/" + finInstnId.getNm();
PostalAddress6 pstlAdr = finInstnId.getPstlAdr();
if (pstlAdr != null) {
List<String> adrLineList = pstlAdr.getAdrLine();
if (adrLineList.size() > 0) {
for (int i=0; i<adrLineList.size(); i++) {
if (i == 4) {
break;
}
String adrLine = adrLineList.get(i);
if (adrLine.length() > 35) {
adrLine = adrLine.substring(0, 35);
}
if (i==0 && StringUtil.isEmpty(field56a)) {
field56a += adrLine;
} else {
field56a += Mx2MtConstants.NEW_LINE+adrLine;
}
}
}
}
}
}
if (StringUtil.isNotEmpty(field56aOption) && StringUtil.isNotEmpty(field56a)) {
map.put("field56aOption", field56aOption);
map.put("field56a", field56a);
}
} catch (Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT900/910 Field56a error");
}
}
private BranchAndFinancialInstitutionIdentification4 getIntrmyAgt1() {
try {
BranchAndFinancialInstitutionIdentification4 intrmyAgt1 = null;
MxCamt05400102 mxCamt05400102 = (MxCamt05400102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05400102 == null || mxCamt05400102.getBkToCstmrDbtCdtNtfctn() == null) {
return null;
}
BankToCustomerDebitCreditNotificationV02 bkToCstmrDbtCdtNtfctn = mxCamt05400102.getBkToCstmrDbtCdtNtfctn();
List<AccountNotification2> ntfctnList = bkToCstmrDbtCdtNtfctn.getNtfctn();
if (ntfctnList != null && ntfctnList.size() > 0) {
AccountNotification2 ntfctn = ntfctnList.get(0);
List<ReportEntry2> ntryList = ntfctn.getNtry();
if (ntryList != null && ntryList.size() > 0) {
ReportEntry2 ntry = ntryList.get(0);
List<EntryDetails1> ntryDtlsList = ntry.getNtryDtls();
if (ntryDtlsList != null && ntryDtlsList.size() > 0) {
EntryDetails1 ntryDtls = ntryDtlsList.get(0);
List<EntryTransaction2> txDtlsList = ntryDtls.getTxDtls();
if (txDtlsList != null && txDtlsList.size() > 0) {
EntryTransaction2 txDtls = txDtlsList.get(0);
TransactionAgents2 rltdAgts = txDtls.getRltdAgts();
if (rltdAgts != null) {
intrmyAgt1 = rltdAgts.getIntrmyAgt1();
}
}
}
}
}
return intrmyAgt1;
} catch (Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT900/910 Field56a error");
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt900910.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.util.StringUtil;
import com.prowidesoftware.swift.model.mx.MxCamt05400102;
import com.prowidesoftware.swift.model.mx.dic.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class Field72Generate extends AbstractMx2MtFieldsGenerate {
private static final Logger logger = LoggerFactory.getLogger(Field72Generate.class);
@Override
public void fieldsGenerate() throws SwiftException {
logger.info("Field72Generate start.");
try {
EntryTransaction2 txDtls = getEntryTransaction2();
if (txDtls != null) {
String addtLtxnInf = txDtls.getAddtlTxInf();
if (StringUtil.isNotEmpty(addtLtxnInf)) {
logger.info(addtLtxnInf);
String field72 = StringUtil.getStringByEnter(addtLtxnInf, 35, 6);
map.put("field72", field72);
}
}
} catch (Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT900/910 Field56a error");
}
}
private EntryTransaction2 getEntryTransaction2() {
try {
EntryTransaction2 txDtls = null;
MxCamt05400102 mxCamt05400102 = (MxCamt05400102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05400102 == null || mxCamt05400102.getBkToCstmrDbtCdtNtfctn() == null) {
return null;
}
BankToCustomerDebitCreditNotificationV02 bkToCstmrDbtCdtNtfctn = mxCamt05400102.getBkToCstmrDbtCdtNtfctn();
List<AccountNotification2> ntfctnList = bkToCstmrDbtCdtNtfctn.getNtfctn();
if (ntfctnList != null && ntfctnList.size() > 0) {
AccountNotification2 ntfctn = ntfctnList.get(0);
List<ReportEntry2> ntryList = ntfctn.getNtry();
if (ntryList != null && ntryList.size() > 0) {
ReportEntry2 ntry = ntryList.get(0);
List<EntryDetails1> ntryDtlsList = ntry.getNtryDtls();
if (ntryDtlsList != null && ntryDtlsList.size() > 0) {
EntryDetails1 ntryDtls = ntryDtlsList.get(0);
List<EntryTransaction2> txDtlsList = ntryDtls.getTxDtls();
if (txDtlsList != null && txDtlsList.size() > 0) {
return txDtlsList.get(0);
}
}
}
}
return txDtls;
} catch (Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT900/910 Field72 error");
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt900910.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.util.StringUtil;
import com.prowidesoftware.swift.model.mx.MxCamt05400102;
import com.prowidesoftware.swift.model.mx.dic.AccountNotification2;
import com.prowidesoftware.swift.model.mx.dic.BankToCustomerDebitCreditNotificationV02;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class ReceiverBicFieldGenerate extends AbstractMx2MtFieldsGenerate{
private static final Logger logger = LoggerFactory.getLogger(ReceiverBicFieldGenerate.class);
/**
* <Stmt><Acct><Svcr><FinInstnId><BICFI>
* @throws SwiftException
*/
@Override
public void fieldsGenerate() throws SwiftException {
logger.info("ReceiverBicFieldGenerate start.");
try {
MxCamt05400102 mxCamt05400102 = (MxCamt05400102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05400102 == null || mxCamt05400102.getBkToCstmrDbtCdtNtfctn() == null) {
return;
}
BankToCustomerDebitCreditNotificationV02 bkToCstmrDbtCdtNtfctn = mxCamt05400102.getBkToCstmrDbtCdtNtfctn();
List<AccountNotification2> ntfctnList = bkToCstmrDbtCdtNtfctn.getNtfctn();
if (ntfctnList != null && ntfctnList.size() > 0) {
AccountNotification2 ntfctn = ntfctnList.get(0);
if (ntfctn != null
&& ntfctn.getAcct() != null
&& ntfctn.getAcct().getSvcr() != null
&& ntfctn.getAcct().getSvcr().getFinInstnId() != null) {
String receiverBic = ntfctn.getAcct().getSvcr().getFinInstnId().getBIC();
String mtReceiverBic = processBicCode(receiverBic);
if (!StringUtil.isEmpty(mtReceiverBic)) {
map.put("receiverBic", mtReceiverBic);
}
}
}
} catch(Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT900/910 ReceiverBic error.");
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt900910.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.util.StringUtil;
import com.prowidesoftware.swift.model.mx.MxCamt05400102;
import com.prowidesoftware.swift.model.mx.dic.AccountNotification2;
import com.prowidesoftware.swift.model.mx.dic.BankToCustomerDebitCreditNotificationV02;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class SenderBicFieldGenerate extends AbstractMx2MtFieldsGenerate {
private static final Logger logger = LoggerFactory.getLogger(SenderBicFieldGenerate.class);
/**
* <Stmt><Acct><Ownr><Id><OrgId><AnyBIC> BICOrBEI
* @throws SwiftException
*/
@Override
public void fieldsGenerate() throws SwiftException {
logger.info("SenderBicFieldGenerate start.");
try {
MxCamt05400102 mxCamt05400102 = (MxCamt05400102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05400102 == null || mxCamt05400102.getBkToCstmrDbtCdtNtfctn() == null) {
return;
}
BankToCustomerDebitCreditNotificationV02 bkToCstmrDbtCdtNtfctn = mxCamt05400102.getBkToCstmrDbtCdtNtfctn();
List<AccountNotification2> ntfctnList = bkToCstmrDbtCdtNtfctn.getNtfctn();
if (ntfctnList != null && ntfctnList.size() > 0) {
AccountNotification2 ntfctn = ntfctnList.get(0);
if (ntfctn != null
&& ntfctn.getAcct() != null
&& ntfctn.getAcct().getOwnr() != null
&& ntfctn.getAcct().getOwnr().getId() != null
&& ntfctn.getAcct().getOwnr().getId().getOrgId() != null) {
String senderBic = ntfctn.getAcct().getOwnr().getId().getOrgId().getBICOrBEI();
String mtSenderBic = processBicCode(senderBic);
if (!StringUtil.isEmpty(mtSenderBic)) {
map.put("senderBic", mtSenderBic);
}
}
}
} catch(Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT900/910 SenderBic error");
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt940950;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtCreator;
import com.prowidesoftware.brilliance.mx2mt.Mx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.mx2mt.mt940950.impl.*;
import com.prowidesoftware.brilliance.util.TemplateUtil;
import com.prowidesoftware.swift.model.mx.MxCamt05300102;
import com.prowidesoftware.swift.model.mx.dic.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
public class Mx2Mt950Creator extends AbstractMx2MtCreator {
private static final Logger logger = LoggerFactory.getLogger(Mx2Mt950Creator.class);
/**
* Object MxCamt05300102
* receiverBic
* senderBic
* field20
* field25a
* field28c
* field60Option
* field60F
* field60A
* field61List
* field62Option
* field62F
* field62M
* field64
*/
@Override
public List<Mx2MtFieldsGenerate> getFieldsGenerateList() {
List<Mx2MtFieldsGenerate> fieldsGenerateList = new ArrayList<>();
if (getMtMsg()){
fieldsGenerateList.add(new Field21Generate());
fieldsGenerateList.add(new Field65Generate());
fieldsGenerateList.add(new Field86Generate());
}
fieldsGenerateList.add(new ReceiverBicFieldGenerate());
fieldsGenerateList.add(new SenderBicFieldGenerate());
fieldsGenerateList.add(new Field20Generate());
fieldsGenerateList.add(new Field25aGenerate());
fieldsGenerateList.add(new Field28CGenerate());
fieldsGenerateList.add(new Field60Generate());
fieldsGenerateList.add(new Field61ListGenerate());
fieldsGenerateList.add(new Field62Generate());
fieldsGenerateList.add(new Field64Generate());
return fieldsGenerateList;
}
@Override
public String generateMtMsg() {
MxCamt05300102 mxCamt05300102 = (MxCamt05300102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05300102 != null
&& mxCamt05300102.getBkToCstmrStmt() != null
&& mxCamt05300102.getBkToCstmrStmt().getGrpHdr() != null) {
generateCommonField(mxCamt05300102.getBkToCstmrStmt().getGrpHdr());
}
map.forEach((key, value) -> {
logger.info(key + "-" + value);
});
String outPutFilePath = (String) map.get(Mx2MtConstants.OUT_PUT_FILE_PATH);
String template;
if (getMtMsg())
template = "swift_mt_940.vm";
else
template = "swift_mt_950.vm";
String msg = TemplateUtil.makeFileByTemplate(template, map, outPutFilePath, "utf-8");
return msg;
}
/**
* 符合以下其中一个条件,则为940,否则为950报文
* (1)<Stmt><Ntry>[j]数组中,节点<AddtlNtryInf>有值
* (2)<Stmt><Bal>[i]数组中,节点<Tp><CdOrPrtry><Cd>值为“FWAV”
* (3)节点<Stmt><AddtlStmtInf>有值
* @return true:940, false:950
*/
public boolean getMtMsg() {
try {
MxCamt05300102 mxCamt05300102 = (MxCamt05300102) map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05300102 == null || mxCamt05300102.getBkToCstmrStmt() == null) {
return false;
}
BankToCustomerStatementV02 bkToCstmrStmt = mxCamt05300102.getBkToCstmrStmt();
List<AccountStatement2> stmtList = bkToCstmrStmt.getStmt();
if (stmtList != null && stmtList.size() > 0) {
AccountStatement2 stmt = stmtList.get(0);
List<ReportEntry2> ntryList = stmt.getNtry();
if (ntryList.size() > 0 && StringUtils.isNotEmpty(ntryList.get(0).getAddtlNtryInf()))
return true;
List<CashBalance3> balList = stmt.getBal();
if (balList != null && balList.size() > 0) {
for (CashBalance3 tmpBal : balList) {
if (tmpBal != null
&& tmpBal.getTp() != null
&& tmpBal.getTp().getCdOrPrtry() != null
&& BalanceType12Code.FWAV.equals(tmpBal.getTp().getCdOrPrtry().getCd())) {
return true;
}
}
}
if (StringUtils.isNotEmpty(stmt.getAddtlStmtInf()))
return true;
return false;
}
} catch (Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Mx2Mt950Creator.getMtMsg() error");
}
return false;
}
}
package com.prowidesoftware.brilliance.mx2mt.mt940950.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.swift.model.mx.MxCamt05300102;
import com.prowidesoftware.swift.model.mx.dic.BankToCustomerStatementV02;
import com.prowidesoftware.swift.model.mx.dic.GroupHeader42;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <GrpHdr><MsgId>
*/
public class Field20Generate extends AbstractMx2MtFieldsGenerate{
private static final Logger logger = LoggerFactory.getLogger(Field20Generate.class);
@Override
public void fieldsGenerate() throws SwiftException{
logger.info("Field20Generate start.");
try {
MxCamt05300102 mxCamt05300102 = (MxCamt05300102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05300102 == null || mxCamt05300102.getBkToCstmrStmt() == null) {
return;
}
BankToCustomerStatementV02 bkToCstmrStmt = mxCamt05300102.getBkToCstmrStmt();
GroupHeader42 grpHdr = bkToCstmrStmt.getGrpHdr();
map.put("field20", grpHdr.getMsgId());
} catch(Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT940/MT950 Field20 error");
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt940950.impl;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
/**
* N/A
*/
public class Field21Generate extends AbstractMx2MtFieldsGenerate {
@Override
public void fieldsGenerate() throws SwiftException {
map.put("field21", "");
}
}
package com.prowidesoftware.brilliance.mx2mt.mt940950.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.util.StringUtil;
import com.prowidesoftware.swift.model.mx.MxCamt05300102;
import com.prowidesoftware.swift.model.mx.dic.AccountIdentification4Choice;
import com.prowidesoftware.swift.model.mx.dic.AccountStatement2;
import com.prowidesoftware.swift.model.mx.dic.BankToCustomerStatementV02;
import com.prowidesoftware.swift.model.mx.dic.GenericAccountIdentification1;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* <Stmt><Acct><Id><IBAN>
* <Stmt><Acct><Id><Othr><Id>
*/
public class Field25aGenerate extends AbstractMx2MtFieldsGenerate{
private static final Logger logger = LoggerFactory.getLogger(Field25aGenerate.class);
@Override
public void fieldsGenerate() throws SwiftException{
logger.info("Field25aGenerate start.");
try {
MxCamt05300102 mxCamt05300102 = (MxCamt05300102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05300102 == null || mxCamt05300102.getBkToCstmrStmt() == null) {
return;
}
BankToCustomerStatementV02 bkToCstmrStmt = mxCamt05300102.getBkToCstmrStmt();
List<AccountStatement2> stmtList = bkToCstmrStmt.getStmt();
if (stmtList != null && stmtList.size() > 0) {
AccountStatement2 accountStatement2 = stmtList.get(0);
if (accountStatement2.getAcct() != null
&& accountStatement2.getAcct().getId() != null) {
AccountIdentification4Choice id = accountStatement2.getAcct().getId();
if (!StringUtil.isEmpty(id.getIBAN())) {
map.put("field25a", id.getIBAN());
} else {
GenericAccountIdentification1 othr = id.getOthr();
if (othr != null) {
map.put("field25a", othr.getId());
}
}
}
}
} catch(Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT940/MT950 Field25a error");
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt940950.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.util.StringUtil;
import com.prowidesoftware.swift.model.mx.MxCamt05300102;
import com.prowidesoftware.swift.model.mx.dic.AccountStatement2;
import com.prowidesoftware.swift.model.mx.dic.BankToCustomerStatementV02;
import com.prowidesoftware.swift.model.mx.dic.GroupHeader42;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.util.List;
/**
* <GrpHdr><MsgPgntn><PgNb>
* <Stmt><ElctrncSeqNb>
*/
public class Field28CGenerate extends AbstractMx2MtFieldsGenerate{
private static final Logger logger = LoggerFactory.getLogger(Field28CGenerate.class);
@Override
public void fieldsGenerate() throws SwiftException{
logger.info("Field28CGenerate start.");
try {
MxCamt05300102 mxCamt05300102 = (MxCamt05300102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05300102 == null || mxCamt05300102.getBkToCstmrStmt() == null) {
return;
}
BankToCustomerStatementV02 bkToCstmrStmt = mxCamt05300102.getBkToCstmrStmt();
BigDecimal seqNb = null;
List<AccountStatement2> stmtList = bkToCstmrStmt.getStmt();
if (stmtList != null && stmtList.size() > 0) {
AccountStatement2 accountStatement2 = stmtList.get(0);
if (accountStatement2 != null) {
seqNb = accountStatement2.getElctrncSeqNb();
}
}
String pgNb = "";
GroupHeader42 grpHdr = bkToCstmrStmt.getGrpHdr();
if (grpHdr != null && grpHdr.getMsgPgntn() != null) {
pgNb = grpHdr.getMsgPgntn().getPgNb();
}
if (seqNb == null && StringUtil.isEmpty(pgNb)) {
throw new SwiftException("ERROR", "Convert MT950 field28C is required!");
} else {
if (seqNb == null) { //only <Stmt><ElctrncSeqNb>
map.put("field28C", pgNb);
} else if (StringUtil.isEmpty(pgNb)) { //only <GrpHdr><MsgPgntn><PgNb>
map.put("field28C", seqNb.toString());
} else { //<Stmt><ElctrncSeqNb> + "/" + GrpHdr><MsgPgntn><PgNb>
map.put("field28C", seqNb.toString() + "/" + pgNb);
}
}
} catch(Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT940/MT950 field28C error");
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt940950.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.util.DateUtil;
import com.prowidesoftware.brilliance.util.NumberUtil;
import com.prowidesoftware.swift.model.mx.MxCamt05300102;
import com.prowidesoftware.swift.model.mx.dic.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.util.List;
/**
* <Stmt><Bal>[i]<Tp><CdOrPrtry><Cd>
* <Stmt><Bal>[i]<CdtDbtInd>
* <Stmt><Bal>[i]<Dt><Dt>
* <Stmt><Bal>[i]<Amt Ccy=“XXX”>
* i = 1
*/
public class Field60Generate extends AbstractMx2MtFieldsGenerate{
private static final Logger logger = LoggerFactory.getLogger(Field60Generate.class);
@Override
public void fieldsGenerate() throws SwiftException{
logger.info("Field60Generate start.");
try {
MxCamt05300102 mxCamt05300102 = (MxCamt05300102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05300102 == null || mxCamt05300102.getBkToCstmrStmt() == null) {
return;
}
BankToCustomerStatementV02 bkToCstmrStmt = mxCamt05300102.getBkToCstmrStmt();
List<AccountStatement2> stmtList = bkToCstmrStmt.getStmt();
if (stmtList != null && stmtList.size() > 0) {
AccountStatement2 stmt = stmtList.get(0);
List<CashBalance3> balList = stmt.getBal();
if (balList != null && balList.size() > 0) {
CashBalance3 bal = balList.get(0);
String filed60Option = "";
if (bal != null && bal.getTp() != null
&& bal.getTp().getCdOrPrtry() != null) {
if (BalanceType12Code.PRCD.equals(bal.getTp().getCdOrPrtry().getCd())) {
filed60Option = "F";
} else if (BalanceType12Code.ITBD.equals(bal.getTp().getCdOrPrtry().getCd())) {
filed60Option = "M";
} else {
throw new SwiftException("ERROR", "cannot find filed60Option.");
}
map.put("filed60Option", filed60Option);
}
if (bal != null) {
String crdr = "";
if (CreditDebitCode.CRDT.equals(bal.getCdtDbtInd())) {
crdr = Mx2MtConstants.DRCRMARK_C;
} else if (CreditDebitCode.DBIT.equals(bal.getCdtDbtInd())) {
crdr = Mx2MtConstants.DRCRMARK_D;
} else {
throw new SwiftException("ERROR", "cannot find filed60 D/C Mark.");
}
String dateStr = "";
if (bal.getDt() != null) {
dateStr = DateUtil.format(bal.getDt().getDt(), "YYMMdd");
}
String ccy = "";
String amtStr = "";
ActiveOrHistoricCurrencyAndAmount ccyAndAmt = bal.getAmt();
if (ccyAndAmt != null) {
ccy = ccyAndAmt.getCcy();
BigDecimal amt = ccyAndAmt.getValue();
amtStr = NumberUtil.formatAmt(amt, ccy);
}
map.put("filed60", crdr+dateStr+ccy+amtStr);
}
}
}
} catch(Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT940/MT950 Field60Generate error");
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt940950.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.util.DateUtil;
import com.prowidesoftware.brilliance.util.NumberUtil;
import com.prowidesoftware.brilliance.util.StringUtil;
import com.prowidesoftware.swift.model.mx.MxCamt05300102;
import com.prowidesoftware.swift.model.mx.dic.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* <Stmt><Ntry>[j]<ValDt><Dt>
* <Stmt><Ntry>[j]<BookgDt><Dt>
* <Stmt><Ntry>[j]<CdtDbtInd>
* <Stmt><Ntry>[j]<RvslInd>
* <Stmt><Ntry>[j]<Sts>
* <Stmt><Ntry>[j]<Amt Ccy=“XXX”>
* <Stmt><Ntry>[j]<BkTxCd><Prtry><Cd>
* <Stmt><Ntry>[j]<NtryDtls><TxDtls><Refs><EndToEndId>
* <Stmt><Ntry>[j]<AcctSvcrRef>
* <Stmt><Ntry>[j]<NtryDtls><TxDtls><AddtlTxInf>
*/
public class Field61ListGenerate extends AbstractMx2MtFieldsGenerate{
private static final Logger logger = LoggerFactory.getLogger(Field61ListGenerate.class);
@Override
public void fieldsGenerate() throws SwiftException{
logger.info("Field61ListGenerate start.");
try {
MxCamt05300102 mxCamt05300102 = (MxCamt05300102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05300102 == null || mxCamt05300102.getBkToCstmrStmt() == null) {
return;
}
BankToCustomerStatementV02 bkToCstmrStmt = mxCamt05300102.getBkToCstmrStmt();
List<AccountStatement2> stmtList = bkToCstmrStmt.getStmt();
if (stmtList != null && stmtList.size() > 0) {
AccountStatement2 stmt = stmtList.get(0);
List<ReportEntry2> ntryList = stmt.getNtry();
if (ntryList.size() > 0) {
List<String> filed61List = new ArrayList<>();
for (int i=0; i<ntryList.size(); i++) {
ReportEntry2 ntry = ntryList.get(i);
String valueDateStr = DateUtil.format(ntry.getValDt().getDt(), "YYMMdd");
String entryDateStr = DateUtil.format(ntry.getBookgDt().getDt(), "YYMMdd");
String drCrMark = "";
if (CreditDebitCode.CRDT.equals(ntry.getCdtDbtInd())) {
if (Boolean.TRUE.equals(ntry.isRvslInd())) {
drCrMark = Mx2MtConstants.DRCRMARK_RD;
} else {
drCrMark = Mx2MtConstants.DRCRMARK_C;
}
} else if (CreditDebitCode.DBIT.equals(ntry.getCdtDbtInd())) {
if (Boolean.TRUE.equals(ntry.isRvslInd())) {
drCrMark = Mx2MtConstants.DRCRMARK_RC;
} else {
drCrMark = Mx2MtConstants.DRCRMARK_D;
}
} else {
throw new SwiftException("ERROR", "cannot find filed61 D/C Mark.");
}
String ccy = "";
String amtStr = "";
ActiveOrHistoricCurrencyAndAmount ccyAndAmt = ntry.getAmt();
if (ccyAndAmt != null) {
ccy = ccyAndAmt.getCcy();
amtStr = NumberUtil.formatAmt(ccyAndAmt.getValue(), ccy);
}
//TODO
String txnTypeAndIdentification = "";
BankTransactionCodeStructure4 bkTxCd = ntry.getBkTxCd();
if (bkTxCd != null) {
ProprietaryBankTransactionCodeStructure1 prtry = bkTxCd.getPrtry();
if (prtry != null) {
txnTypeAndIdentification = prtry.getCd();
}
}
String referenceForTheAccountOwner = "";
String supplementDetails = "";
List<EntryDetails1> ntryDtlsList = ntry.getNtryDtls();
if (ntryDtlsList.size() > 0) {
EntryDetails1 ntryDtls = ntryDtlsList.get(0);
List<EntryTransaction2> txDtlsList = ntryDtls.getTxDtls();
if (txDtlsList.size() > 0) {
EntryTransaction2 txDtls = txDtlsList.get(0);
if (txDtls.getRefs() != null) {
referenceForTheAccountOwner = txDtls.getRefs().getEndToEndId();
}
supplementDetails = txDtls.getAddtlTxInf();
}
}
String referenceForTheAccountServInst = ntry.getAcctSvcrRef();
StringBuilder sb = new StringBuilder();
sb.append(valueDateStr)
.append(entryDateStr)
.append(drCrMark)
.append(ccy)
.append(amtStr)
.append(txnTypeAndIdentification)
.append(referenceForTheAccountOwner);
if (!StringUtil.isEmpty(referenceForTheAccountServInst)) {
sb.append("//"+referenceForTheAccountServInst);
}
if (!StringUtil.isEmpty(supplementDetails)) {
sb.append(Mx2MtConstants.NEW_LINE+supplementDetails);
}
if (StringUtils.isNotEmpty(ntry.getAddtlNtryInf()))
sb.append(Mx2MtConstants.NEW_LINE).append(":86:").append(StringUtil.getStringByEnter(ntry.getAddtlNtryInf(), 35, 6));
filed61List.add(sb.toString());
}
if (filed61List.size() > 0) {
filed61List.forEach(field61 -> logger.info(":61:"+field61));
map.put("filed61List", filed61List);
}
}
}
} catch(Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT940/MT950 Field61List error");
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt940950.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.util.DateUtil;
import com.prowidesoftware.brilliance.util.NumberUtil;
import com.prowidesoftware.swift.model.mx.MxCamt05300102;
import com.prowidesoftware.swift.model.mx.dic.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.util.List;
/**
* <Stmt><Bal>[i]<Tp><CdOrPrtry><Cd>
* <Stmt><Bal>[i]<CdtDbtInd>
* <Stmt><Bal>[i]<Dt><Dt>
* <Stmt><Bal>[i]<Amt Ccy=“XXX”
* i = 2
*/
public class Field62Generate extends AbstractMx2MtFieldsGenerate{
private static final Logger logger = LoggerFactory.getLogger(Field62Generate.class);
@Override
public void fieldsGenerate() throws SwiftException{
logger.info("Field62Generate start.");
try {
MxCamt05300102 mxCamt05300102 = (MxCamt05300102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05300102 == null || mxCamt05300102.getBkToCstmrStmt() == null) {
return;
}
BankToCustomerStatementV02 bkToCstmrStmt = mxCamt05300102.getBkToCstmrStmt();
List<AccountStatement2> stmtList = bkToCstmrStmt.getStmt();
if (stmtList != null && stmtList.size() > 0) {
AccountStatement2 stmt = stmtList.get(0);
List<CashBalance3> balList = stmt.getBal();
if (balList != null && balList.size() >= 2) {
CashBalance3 bal = balList.get(1);
String filed62Option = "";
if (bal != null && bal.getTp() != null
&& bal.getTp().getCdOrPrtry() != null) {
if (BalanceType12Code.CLBD.equals(bal.getTp().getCdOrPrtry().getCd())) {
filed62Option = "F";
} else if (BalanceType12Code.ITBD.equals(bal.getTp().getCdOrPrtry().getCd())) {
filed62Option = "M";
} else {
throw new SwiftException("ERROR", "cannot find filed62Option.");
}
map.put("filed62Option", filed62Option);
}
if (bal != null) {
String crdr = "";
if (CreditDebitCode.CRDT.equals(bal.getCdtDbtInd())) {
crdr = Mx2MtConstants.DRCRMARK_C;
} else if (CreditDebitCode.DBIT.equals(bal.getCdtDbtInd())) {
crdr = Mx2MtConstants.DRCRMARK_D;
} else {
throw new SwiftException("ERROR", "cannot find filed60 D/C Mark.");
}
String dateStr = "";
if (bal.getDt() != null) {
dateStr = DateUtil.format(bal.getDt().getDt(), "YYMMdd");
}
String ccy = "";
String amtStr = "";
ActiveOrHistoricCurrencyAndAmount ccyAndAmt = bal.getAmt();
if (ccyAndAmt != null) {
ccy = ccyAndAmt.getCcy();
BigDecimal amt = ccyAndAmt.getValue();
amtStr = NumberUtil.formatAmt(amt, ccy);
}
map.put("filed62", crdr+dateStr+ccy+amtStr);
}
}
}
} catch(Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT940/MT950 Field62 error");
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt940950.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.util.DateUtil;
import com.prowidesoftware.brilliance.util.NumberUtil;
import com.prowidesoftware.swift.model.mx.MxCamt05300102;
import com.prowidesoftware.swift.model.mx.dic.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.util.List;
/**
* <Stmt><Bal>[i]<Tp><CdOrPrtry><Cd>
* <Stmt><Bal>[i]<CdtDbtInd>
* <Stmt><Bal>[i]<Dt><Dt>
* <Stmt><Bal>[i]<Amt Ccy=“XXX”
* LOOP BAL
* IF CLAV == <Bal><Tp><CdOrPrtry><Cd> means exist 64
*/
public class Field64Generate extends AbstractMx2MtFieldsGenerate{
private static final Logger logger = LoggerFactory.getLogger(Field64Generate.class);
@Override
public void fieldsGenerate() throws SwiftException{
logger.info("Field64Generate start.");
try {
MxCamt05300102 mxCamt05300102 = (MxCamt05300102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05300102 == null || mxCamt05300102.getBkToCstmrStmt() == null) {
return;
}
BankToCustomerStatementV02 bkToCstmrStmt = mxCamt05300102.getBkToCstmrStmt();
List<AccountStatement2> stmtList = bkToCstmrStmt.getStmt();
if (stmtList != null && stmtList.size() > 0) {
AccountStatement2 stmt = stmtList.get(0);
List<CashBalance3> balList = stmt.getBal();
CashBalance3 bal = null;
if (balList != null && balList.size() > 0) {
for (CashBalance3 tmpBal : balList) {
if (tmpBal != null
&& tmpBal.getTp() != null
&& tmpBal.getTp().getCdOrPrtry() != null
&& BalanceType12Code.CLAV.equals(tmpBal.getTp().getCdOrPrtry().getCd())) {
bal = tmpBal;
break;
}
}
}
if (bal != null) { //exist 64
String crdr = "";
if (CreditDebitCode.CRDT.equals(bal.getCdtDbtInd())) {
crdr = Mx2MtConstants.DRCRMARK_C;
} else if (CreditDebitCode.DBIT.equals(bal.getCdtDbtInd())) {
crdr = Mx2MtConstants.DRCRMARK_D;
} else {
throw new SwiftException("ERROR", "cannot find filed64 D/C Mark.");
}
String dateStr = "";
if (bal.getDt() != null) {
dateStr = DateUtil.format(bal.getDt().getDt(), "YYMMdd");
}
String ccy = "";
String amtStr = "";
ActiveOrHistoricCurrencyAndAmount ccyAndAmt = bal.getAmt();
if (ccyAndAmt != null) {
ccy = ccyAndAmt.getCcy();
BigDecimal amt = ccyAndAmt.getValue();
amtStr = NumberUtil.formatAmt(amt, ccy);
}
String filed64 = crdr+dateStr+ccy+amtStr;
map.put("filed64", filed64);
}
}
} catch(Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT940/MT950 filed64 error");
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt940950.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.util.DateUtil;
import com.prowidesoftware.brilliance.util.NumberUtil;
import com.prowidesoftware.swift.model.mx.MxCamt05300102;
import com.prowidesoftware.swift.model.mx.dic.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.util.List;
/**
* <Stmt><Bal>[i]<Tp><CdOrPrtry><Cd>
* <Stmt><Bal>[i]<CdtDbtInd>
* <Stmt><Bal>[i]<Dt><Dt>
* <Stmt><Bal>[i]<Amt Ccy=“XXX”>
* LOOP BAL
* IF CLAV == <Bal><Tp><CdOrPrtry><Cd> means exist 65
*/
public class Field65Generate extends AbstractMx2MtFieldsGenerate {
private static final Logger logger = LoggerFactory.getLogger(Field65Generate.class);
@Override
public void fieldsGenerate() throws SwiftException{
logger.info("Field65Generate start.");
try {
MxCamt05300102 mxCamt05300102 = (MxCamt05300102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05300102 == null || mxCamt05300102.getBkToCstmrStmt() == null) {
return;
}
BankToCustomerStatementV02 bkToCstmrStmt = mxCamt05300102.getBkToCstmrStmt();
List<AccountStatement2> stmtList = bkToCstmrStmt.getStmt();
if (stmtList != null && stmtList.size() > 0) {
AccountStatement2 stmt = stmtList.get(0);
List<CashBalance3> balList = stmt.getBal();
CashBalance3 bal = null;
if (balList != null && balList.size() > 0) {
for (CashBalance3 tmpBal : balList) {
if (tmpBal != null
&& tmpBal.getTp() != null
&& tmpBal.getTp().getCdOrPrtry() != null
&& BalanceType12Code.FWAV.equals(tmpBal.getTp().getCdOrPrtry().getCd())) {
bal = tmpBal;
break;
}
}
}
if (bal != null) { //exist 65
String crdr = "";
if (CreditDebitCode.CRDT.equals(bal.getCdtDbtInd())) {
crdr = Mx2MtConstants.DRCRMARK_C;
} else if (CreditDebitCode.DBIT.equals(bal.getCdtDbtInd())) {
crdr = Mx2MtConstants.DRCRMARK_D;
} else {
throw new SwiftException("ERROR", "cannot find filed65 D/C Mark.");
}
String dateStr = "";
if (bal.getDt() != null) {
dateStr = DateUtil.format(bal.getDt().getDt(), "YYMMdd");
}
String ccy = "";
String amtStr = "";
ActiveOrHistoricCurrencyAndAmount ccyAndAmt = bal.getAmt();
if (ccyAndAmt != null) {
ccy = ccyAndAmt.getCcy();
BigDecimal amt = ccyAndAmt.getValue();
amtStr = NumberUtil.formatAmt(amt, ccy);
}
String filed65 = crdr+dateStr+ccy+amtStr;
map.put("field65", filed65);
}
}
} catch(Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT940 filed65 error");
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt940950.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.util.StringUtil;
import com.prowidesoftware.swift.model.mx.MxCamt05300102;
import com.prowidesoftware.swift.model.mx.dic.AccountStatement2;
import com.prowidesoftware.swift.model.mx.dic.BankToCustomerStatementV02;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
*<Stmt><AddtlStmtInf>
*
*/
public class Field86Generate extends AbstractMx2MtFieldsGenerate {
private static final Logger logger = LoggerFactory.getLogger(Field86Generate.class);
@Override
public void fieldsGenerate() throws SwiftException {
logger.info("Field86Generate start");
try {
MxCamt05300102 mxCamt05300102 = (MxCamt05300102) map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05300102 == null || mxCamt05300102.getBkToCstmrStmt() == null) {
return;
}
BankToCustomerStatementV02 bkToCstmrStmt = mxCamt05300102.getBkToCstmrStmt();
List<AccountStatement2> stmtList = bkToCstmrStmt.getStmt();
if (stmtList != null && stmtList.size() > 0) {
AccountStatement2 stmt = stmtList.get(0);
if (StringUtils.isNotEmpty(stmt.getAddtlStmtInf())) {
map.put("field86", StringUtil.getStringByEnter(stmt.getAddtlStmtInf(), 35, 6));
}
}
} catch (Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT940 filed86 error");
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt940950.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.util.StringUtil;
import com.prowidesoftware.swift.model.mx.MxCamt05300102;
import com.prowidesoftware.swift.model.mx.dic.AccountStatement2;
import com.prowidesoftware.swift.model.mx.dic.BankToCustomerStatementV02;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class ReceiverBicFieldGenerate extends AbstractMx2MtFieldsGenerate{
private static final Logger logger = LoggerFactory.getLogger(ReceiverBicFieldGenerate.class);
/**
* <Stmt><Acct><Svcr><FinInstnId><BICFI>
* @throws SwiftException
*/
@Override
public void fieldsGenerate() throws SwiftException{
logger.info("ReceiverBicFieldGenerate start.");
try {
MxCamt05300102 mxCamt05300102 = (MxCamt05300102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05300102 == null || mxCamt05300102.getBkToCstmrStmt() == null) {
return;
}
BankToCustomerStatementV02 bkToCstmrStmt = mxCamt05300102.getBkToCstmrStmt();
List<AccountStatement2> stmtList = bkToCstmrStmt.getStmt();
if (stmtList != null && stmtList.size() > 0) {
AccountStatement2 accountStatement2 = stmtList.get(0);
if (accountStatement2 != null
&& accountStatement2.getAcct() != null
&& accountStatement2.getAcct().getSvcr() != null
&& accountStatement2.getAcct().getSvcr().getFinInstnId() != null) {
String receiverBic = accountStatement2.getAcct().getSvcr().getFinInstnId().getBIC();
String mtReceiverBic = processBicCode(receiverBic);
if (!StringUtil.isEmpty(mtReceiverBic)) {
map.put("receiverBic", mtReceiverBic);
}
}
}
} catch(Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT950 ReceiverBic error.");
}
}
}
package com.prowidesoftware.brilliance.mx2mt.mt940950.impl;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import com.prowidesoftware.brilliance.exception.SwiftException;
import com.prowidesoftware.brilliance.mx2mt.AbstractMx2MtFieldsGenerate;
import com.prowidesoftware.brilliance.util.StringUtil;
import com.prowidesoftware.swift.model.mx.MxCamt05300102;
import com.prowidesoftware.swift.model.mx.dic.AccountStatement2;
import com.prowidesoftware.swift.model.mx.dic.BankToCustomerStatementV02;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class SenderBicFieldGenerate extends AbstractMx2MtFieldsGenerate {
private static final Logger logger = LoggerFactory.getLogger(SenderBicFieldGenerate.class);
/**
* <Stmt><Acct><Ownr><Id><OrgId><AnyBIC> BICOrBEI
* @throws SwiftException
*/
@Override
public void fieldsGenerate() throws SwiftException{
logger.info("SenderBicFieldGenerate start.");
try {
MxCamt05300102 mxCamt05300102 = (MxCamt05300102)map.get(Mx2MtConstants.MX_OBJECT);
if (mxCamt05300102 == null || mxCamt05300102.getBkToCstmrStmt() == null) {
return;
}
BankToCustomerStatementV02 bkToCstmrStmt = mxCamt05300102.getBkToCstmrStmt();
List<AccountStatement2> stmtList = bkToCstmrStmt.getStmt();
if (stmtList != null && stmtList.size() > 0) {
AccountStatement2 accountStatement2 = stmtList.get(0);
if (accountStatement2 != null
&& accountStatement2.getAcct() != null
&& accountStatement2.getAcct().getOwnr() != null
&& accountStatement2.getAcct().getOwnr().getId() != null
&& accountStatement2.getAcct().getOwnr().getId().getOrgId() != null) {
String senderBic = accountStatement2.getAcct().getOwnr().getId().getOrgId().getBICOrBEI();
String mtSenderBic = processBicCode(senderBic);
if (!StringUtil.isEmpty(mtSenderBic)) {
map.put("senderBic", mtSenderBic);
}
}
}
} catch(Exception e) {
logger.error(e.getMessage());
throw new SwiftException("ERROR", "Convert MT950 SenderBic error");
}
}
}
package com.prowidesoftware.brilliance.spi;
import com.prowidesoftware.brilliance.util.ClassUtil;
import com.prowidesoftware.brilliance.util.PropertyUtil;
import com.prowidesoftware.brilliance.util.ReflectionUtil;
import com.prowidesoftware.brilliance.util.StringUtil;
import org.springframework.core.OrderComparator;
import org.springframework.util.Assert;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;
/**
* spi加载类
*/
public class BeSpiLoader {
public static final String SERVICES_RESOURCE_LOCATION = "META-INF/be-esb.services";
public static final String COMMA_DELIMITED = ",";
static final com.prowidesoftware.brilliance.spi.ConcurrentReferenceMap<ClassLoader, Map<String, List<String>>> cache = new ConcurrentReferenceMap<ClassLoader, Map<String, List<String>>>();
private BeSpiLoader() {
}
public static <T> List<T> loadBeServices(Class<T> serviceType, ClassLoader classLoader) {
return loadBeServices(serviceType, classLoader, null, null);
}
public static <T> List<T> loadBeServices(Class<T> serviceType, ClassLoader classLoader, Object[] args, Class[] argsTypes) {
Assert.notNull(serviceType, "'serviceType' must not be null");
ClassLoader classLoaderToUse = classLoader;
if (classLoaderToUse == null) {
classLoaderToUse = BeSpiLoader.class.getClassLoader();
}
List<String> serviceImplementationNames = loadServiceNames(serviceType, classLoaderToUse);
List<T> result = new ArrayList<>(serviceImplementationNames.size());
for (String serviceImplementationName : serviceImplementationNames) {
result.add(instantiateService(serviceImplementationName, serviceType, classLoaderToUse, args, argsTypes));
}
OrderComparator.sort(result);
return result;
}
public static List<String> loadServiceNames(Class<?> serviceType, ClassLoader classLoader) {
ClassLoader classLoaderToUse = classLoader;
if (classLoaderToUse == null) {
classLoaderToUse = BeSpiLoader.class.getClassLoader();
}
String serviceTypeName = serviceType.getName();
return loadBeServices(classLoaderToUse).getOrDefault(serviceTypeName, Collections.emptyList());
}
private static Map<String, List<String>> loadBeServices(ClassLoader classLoader) {
Map<String, List<String>> result = cache.get(classLoader);
if (result != null) {
return result;
}
try {
Enumeration<URL> urls = classLoader.getResources(SERVICES_RESOURCE_LOCATION);
result = new HashMap<String, List<String>>();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
Properties properties = PropertyUtil.loadProperties(url);
for (Map.Entry<?, ?> entry : properties.entrySet()) {
String serviceTypeName = ((String) entry.getKey()).trim();
String[] serviceImplementationNames = ((String) entry.getValue()).split(COMMA_DELIMITED);
for (String serviceImplementationName : serviceImplementationNames) {
if(StringUtil.isEmpty(serviceImplementationName)){
continue;
}
result.computeIfAbsent(serviceTypeName, key -> new ArrayList<>())
.add(serviceImplementationName.trim());
}
}
}
// 去重,并且转换为不能修改得list,按key为classLoader缓存到map
result.replaceAll((serviceType, implementations) -> implementations.stream().distinct()
.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)));
cache.put(classLoader, result);
} catch (IOException ex) {
throw new IllegalArgumentException("Unable to load services from location [" +
SERVICES_RESOURCE_LOCATION + "]", ex);
}
return result;
}
@SuppressWarnings("unchecked")
private static <T> T instantiateService(String serviceImplementationName, Class<T> serviceType,
ClassLoader classLoader, Object[] args, Class[] argsTypes) {
try {
Class<?> serviceImplementationClass = ClassUtil.forName(serviceImplementationName, classLoader);
if (!serviceType.isAssignableFrom(serviceImplementationClass)) {
throw new IllegalArgumentException(
"Class [" + serviceImplementationName + "] is not assignable to type [" + serviceType.getName() + "]");
}
if (args == null) {
return (T) ReflectionUtil.accessibleConstructor(serviceImplementationClass).newInstance();
} else {
try{
return (T) ReflectionUtil.accessibleConstructor(serviceImplementationClass, argsTypes).newInstance(args);
}catch (NoSuchMethodException e){
//尝试采用无参构造函数创建实例
return (T) ReflectionUtil.accessibleConstructor(serviceImplementationClass).newInstance();
}
}
} catch (Throwable ex) {
throw new IllegalArgumentException(
"Unable to instantiate class [" + serviceImplementationName + "] for type [" + serviceType.getName() + "]",
ex);
}
}
}
package com.prowidesoftware.brilliance.spi;
import com.prowidesoftware.brilliance.util.ObjectUtil;
import org.springframework.util.Assert;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.concurrent.ConcurrentHashMap;
/**
* 对ConcurrentHashMap的封装,目的是通过值的引用封装,从而在JVM内存吃紧时GC时会自动释放内存。对于用户操作键值对却是无感的。
* <p><b>注意:</b>引用的使用意味着不能保证放置到Map中的键值对随后可用。垃圾收集器可能会随时丢弃引用,因此可能会出现未知线程正在悄悄删除键值对。</p>
* <p>支持ReferenceType.SOFT或ReferenceType.WEAK类型引用,默认为SOFT。</p>
*/
public class ConcurrentReferenceMap<T, S> {
private static final ReferenceType DEFAULT_REFERENCE_TYPE = ReferenceType.SOFT;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
private final ConcurrentHashMap<T, Reference<S>> cache;
private final ReferenceType referenceType;
/**
* 空构造ConcurrentReferenceMap。使用默认引用类型SOFT和默认缓存初始容量16
*/
public ConcurrentReferenceMap() {
this(DEFAULT_REFERENCE_TYPE, DEFAULT_INITIAL_CAPACITY);
}
/**
* 构造一个初始容量为initialCapacity的ConcurrentReferenceMap。使用默认引用类型SOFT
* @param initialCapacity 初始容量大小
*/
public ConcurrentReferenceMap(int initialCapacity) {
this(DEFAULT_REFERENCE_TYPE, initialCapacity);
}
/**
* 构造一个指定引用类型和初始容量的ConcurrentReferenceMap。
* @param referenceType 引用类型(ReferenceType.SOFT或ReferenceType.WEAK)
* @param initialCapacity
*/
public ConcurrentReferenceMap(ReferenceType referenceType, int initialCapacity) {
this.cache = new ConcurrentHashMap<>(initialCapacity);
this.referenceType = referenceType;
}
public S get(Object key) {
Assert.notNull(key, "key must not be null");
Reference<S> sReference = cache.get(key);
if (ObjectUtil.isNull(sReference)) {
return null;
}
return sReference.get();
}
public S getOrDefault(Object key, S defaultValue) {
S v;
return (v = get(key)) == null ? defaultValue : v;
}
public S put(T key, S value) {
Assert.notNull(key, "key must not be null");
Assert.notNull(value, "value must not be null");
Reference<S> oldref = null;
if (value instanceof Reference) {
oldref = cache.put(key, (Reference<S>) value);
} else {
oldref = cache.put(key, referenceType.generateReference(value));
}
return ObjectUtil.isNull(oldref) ? null : oldref.get();
}
public void clear(){
cache.clear();
}
/**
* 强制清理值为空的键值对
*/
public void clearUnreferencedEntries() {
cache.entrySet().removeIf(entry -> ObjectUtil.isNull(entry.getValue()));
}
public enum ReferenceType {
SOFT {
@Override
Reference generateReference(Object value) {
return new SoftReference(value);
}
}, WEAK {
@Override
Reference generateReference(Object value) {
return new WeakReference(value);
}
};
abstract Reference generateReference(Object value);
}
}
package com.prowidesoftware.brilliance.test;
import com.prowidesoftware.brilliance.mx2mt.Mx2MtCreateManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
public class ConvertMx2Mt {
public static Logger logger = LoggerFactory.getLogger(ConvertMx2Mt.class);
public static void main(String[] args) {
String xmlPath=args[0];
String outPath=args[1];
logger.info("xmlPath="+xmlPath);
Mx2MtCreateManager mx2MtCreateManager=new Mx2MtCreateManager();
try {
String str= mx2MtCreateManager.mx2mt(new File(xmlPath),outPath);
System.out.println(str);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.prowidesoftware.brilliance.util;
/**
* 数组工具
*/
public class ArrayUtil {
/**
* 数组是否为空
*
* @param array 对象数组
* @return 是否为空
*/
public static boolean isEmpty(Object[] array) {
return array == null || array.length == 0;
}
/**
* 数组是否为空
*
* @param array long成员数组
* @return 是否为空
*/
public static boolean isEmpty(long[] array) {
return array == null || array.length == 0;
}
/**
* 数组是否为空
*
* @param array int成员数组
* @return 是否为空
*/
public static boolean isEmpty(int[] array) {
return array == null || array.length == 0;
}
/**
* 数组是否为空
*
* @param array 数组
* @return 是否为空
*/
public static boolean isEmpty(short[] array) {
return array == null || array.length == 0;
}
/**
* 数组是否为空
*
* @param array char成员数组
* @return 是否为空
*/
public static boolean isEmpty(char[] array) {
return array == null || array.length == 0;
}
/**
* 数组是否为空
*
* @param array double成员数组
* @return 是否为空
*/
public static boolean isEmpty(double[] array) {
return array == null || array.length == 0;
}
/**
* 数组是否为空
*
* @param array float成员数组
* @return 是否为空
*/
public static boolean isEmpty(float[] array) {
return array == null || array.length == 0;
}
/**
* 数组是否为空
*
* @param array boolean成员数组
* @return 是否为空
*/
public static boolean isEmpty(boolean[] array) {
return array == null || array.length == 0;
}
/**
* 数组是否为空
*
* @param array byte成员数组
* @return 是否为空
*/
public static boolean isEmpty(byte[] array) {
return array == null || array.length == 0;
}
public static boolean contains(char[] array, char value) {
return indexOf(array, value) > -1;
}
public static int indexOf(char[] array, char value) {
if (null != array) {
for (int i = 0; i < array.length; ++i) {
if (value == array[i]) {
return i;
}
}
}
return -1;
}
/**
* 生成一个新的重新设置大小的数组<br>
* 调整大小后拷贝原数组到新数组下。扩大则占位前N个位置,其它位置补充0,缩小则截断
*
* @param bytes 原数组
* @param newSize 新的数组大小
* @return 调整后的新数组
*/
public static byte[] resize(byte[] bytes, int newSize) {
if (newSize < 0) {
return bytes;
}
final byte[] newArray = new byte[newSize];
if (newSize > 0 && !isEmpty(bytes)) {
System.arraycopy(bytes, 0, newArray, 0, Math.min(bytes.length, newSize));
}
return newArray;
}
/**
* 包装 {@link System#arraycopy(Object, int, Object, int, int)}<br>
* 数组复制,缘数组和目标数组都是从位置0开始复制
*
* @param src 源数组
* @param dest 目标数组
* @param length 拷贝数组长度
* @return 目标数组
*/
public static Object copy(Object src, Object dest, int length) {
System.arraycopy(src, 0, dest, 0, length);
return dest;
}
}
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.prowidesoftware.brilliance.util;
import com.prowidesoftware.brilliance.exception.CommonRuntimeException;
import org.apache.commons.lang.ClassUtils;
import org.springframework.util.Assert;
import java.io.Closeable;
import java.io.Externalizable;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
/**
* Class工具类
*/
public abstract class ClassUtil {
public static final String CLASS_EXTENSION = ".class";
public static final String JAVA_EXTENSION = ".java";
/**
* 数组类名的后缀: {@code "[]"}.
*/
public static final String ARRAY_SUFFIX = "[]";
/**
* 内部数组类名的前缀: {@code "["}.
*/
private static final String INTERNAL_ARRAY_PREFIX = "[";
/**
* 内部非原始数组类名的前缀: {@code "[L"}.
*/
private static final String NON_PRIMITIVE_ARRAY_PREFIX = "[L";
/**
* 包分隔符: {@code '.'}.
*/
private static final char PACKAGE_SEPARATOR = '.';
/**
* 嵌套的类分隔符: {@code '$'}.
*/
private static final char NESTED_CLASS_SEPARATOR = '$';
/**
* 以原始包装类型为键,对应原始类型为值的映射, 例如: Integer.class -> int.class.
*/
private static final Map<Class<?>, Class<?>> primitiveWrapperTypeMap = new IdentityHashMap<>(9);
/**
* 以原始类型为键和相应的包装器类型为值的映射, 例如: int.class -> Integer.class.
*/
private static final Map<Class<?>, Class<?>> primitiveTypeToWrapperMap = new IdentityHashMap<>(9);
/**
* 以原始类型名称为键,对应原始类型为值的映射, for example: "int" -> "int.class".
*/
private static final Map<String, Class<?>> primitiveTypeNameMap = new HashMap<>(32);
/**
* 通用的一些类型为键,对应的类为值的映射。 * 主要用于远程调用的高效反序列化。
*/
private static final Map<String, Class<?>> commonClassCache = new HashMap<>(64);
static {
primitiveWrapperTypeMap.put(Boolean.class, boolean.class);
primitiveWrapperTypeMap.put(Byte.class, byte.class);
primitiveWrapperTypeMap.put(Character.class, char.class);
primitiveWrapperTypeMap.put(Double.class, double.class);
primitiveWrapperTypeMap.put(Float.class, float.class);
primitiveWrapperTypeMap.put(Integer.class, int.class);
primitiveWrapperTypeMap.put(Long.class, long.class);
primitiveWrapperTypeMap.put(Short.class, short.class);
primitiveWrapperTypeMap.put(Void.class, void.class);
// Map entry iteration is less expensive to initialize than forEach with lambdas
for (Map.Entry<Class<?>, Class<?>> entry : primitiveWrapperTypeMap.entrySet()) {
primitiveTypeToWrapperMap.put(entry.getValue(), entry.getKey());
registerCommonClasses(entry.getKey());
}
Set<Class<?>> primitiveTypes = new HashSet<>(32);
primitiveTypes.addAll(primitiveWrapperTypeMap.values());
Collections.addAll(primitiveTypes, boolean[].class, byte[].class, char[].class,
double[].class, float[].class, int[].class, long[].class, short[].class);
for (Class<?> primitiveType : primitiveTypes) {
primitiveTypeNameMap.put(primitiveType.getName(), primitiveType);
}
registerCommonClasses(Boolean[].class, Byte[].class, Character[].class, Double[].class,
Float[].class, Integer[].class, Long[].class, Short[].class);
registerCommonClasses(Number.class, Number[].class, String.class, String[].class,
Class.class, Class[].class, Object.class, Object[].class);
registerCommonClasses(Throwable.class, Exception.class, RuntimeException.class,
Error.class, StackTraceElement.class, StackTraceElement[].class);
registerCommonClasses(Enum.class, Iterable.class, Iterator.class, Enumeration.class,
Collection.class, List.class, Set.class, Map.class, Map.Entry.class, Optional.class);
Class<?>[] javaLanguageInterfaceArray = {Serializable.class, Externalizable.class,
Closeable.class, AutoCloseable.class, Cloneable.class, Comparable.class};
registerCommonClasses(javaLanguageInterfaceArray);
}
/**
* 缓存一些常用的公共类(类名为键,类型为值).
*/
private static void registerCommonClasses(Class<?>... commonClasses) {
for (Class<?> clazz : commonClasses) {
commonClassCache.put(clazz.getName(), clazz);
}
}
public static ClassLoader getDefaultClassLoader() {
ClassLoader cl = null;
try {
cl = Thread.currentThread().getContextClassLoader();
} catch (Throwable ex) {
// Cannot access thread context ClassLoader - falling back...
}
if (cl == null) {
// No thread context class loader -> use class loader of this class.
cl = ClassUtils.class.getClassLoader();
if (cl == null) {
// getClassLoader() returning null indicates the bootstrap ClassLoader
try {
cl = ClassLoader.getSystemClassLoader();
} catch (Throwable ex) {
// Cannot access system ClassLoader - oh well, maybe the caller can live with null...
}
}
}
return cl;
}
/**
* Class.forName()优化,它也返回基础类型(例如“int”)和数组类名称(例如“String[]”)的类实例。
* 此外,它还能够解析Java源代码样式中的嵌套类名(例如“java.lang.Thread$State”来代替“java.lang.Thread.State”)
*
* @param name 类名称
* @param classLoader 可以为空,则使用默认类加载器
* @return 所提供名称的类实例
* @throws ClassNotFoundException 如果类没有被发现
* @throws LinkageError 如果类文件不能被加载
*/
public static Class<?> forName(String name, ClassLoader classLoader)
{
Assert.notNull(name, "Name must not be null");
Class<?> clazz = resolvePrimitiveClassName(name);
if (clazz == null) {
clazz = commonClassCache.get(name);
}
if (clazz != null) {
return clazz;
}
//支持各种形式得数组命名转换
// "java.lang.String[]" 数组样式
if (name.endsWith(ARRAY_SUFFIX)) {
String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length());
Class<?> elementClass = forName(elementClassName, classLoader);
return Array.newInstance(elementClass, 0).getClass();
}
// "[Ljava.lang.String;" 数组样式
if (name.startsWith(NON_PRIMITIVE_ARRAY_PREFIX) && name.endsWith(";")) {
String elementName = name.substring(NON_PRIMITIVE_ARRAY_PREFIX.length(), name.length() - 1);
Class<?> elementClass = forName(elementName, classLoader);
return Array.newInstance(elementClass, 0).getClass();
}
// "[[I" or "[[Ljava.lang.String;" 数组样式
if (name.startsWith(INTERNAL_ARRAY_PREFIX)) {
String elementName = name.substring(INTERNAL_ARRAY_PREFIX.length());
Class<?> elementClass = forName(elementName, classLoader);
return Array.newInstance(elementClass, 0).getClass();
}
ClassLoader clToUse = classLoader;
if (clToUse == null) {
clToUse = getDefaultClassLoader();
}
try {
return Class.forName(name, false, clToUse);
} catch (ClassNotFoundException ex) {
int lastDotIndex = name.lastIndexOf(PACKAGE_SEPARATOR);
if (lastDotIndex != -1) {
String nestedClassName =
name.substring(0, lastDotIndex) + NESTED_CLASS_SEPARATOR + name.substring(lastDotIndex + 1);
try {
return Class.forName(nestedClassName, false, clToUse);
} catch (ClassNotFoundException ex2) {
// 静默处理- 让原始异常通过
}
}
throw new CommonRuntimeException("Class Not Found Exception",ex);
}
}
/**
* 确定由提供的名称标识的class是否存在,并且可以加载。如果类或其依赖项之一不存在或无法加载,则将返回 {@code false}
*
* @param className 类名称
* @param classLoader 可以为空,则使用默认类加载器
* @return true表示类存在
*/
public static boolean isPresent(String className, ClassLoader classLoader) {
try {
forName(className, classLoader);
return true;
} catch (IllegalAccessError err) {
throw new IllegalStateException("Readability mismatch in inheritance hierarchy of class [" +
className + "]: " + err.getMessage(), err);
} catch (Throwable ex) {
// Typically ClassNotFoundException or NoClassDefFoundError...
return false;
}
}
public static Class<?> resolvePrimitiveClassName(String name) {
Class<?> result = null;
// 大多数类名会很长,考虑到它们应该放在一个包中,所以长度检查是值得的.
if (name != null && name.length() <= 7) {
result = primitiveTypeNameMap.get(name);
}
return result;
}
/**
* 确定提供的类是否是内部类,即封闭类的非静态成员
*
* @return 如果提供的类是非静态内部类返回true
*/
public static boolean isInnerClass(Class<?> clazz) {
return (clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers()));
}
/**
* 检查右侧类型是否可以分配给左侧类型。 将原始包装类视为可分配给相应的原始类型
*
* @param lhsType 目标类型
* @param rhsType 应分配给目标类型的值类型
* @return 如果右侧类型可以赋值给左侧类型,则返回true
*/
public static boolean isAssignable(Class<?> lhsType, Class<?> rhsType) {
Assert.notNull(lhsType, "Left-hand side type must not be null");
Assert.notNull(rhsType, "Right-hand side type must not be null");
if (lhsType.isAssignableFrom(rhsType)) {
return true;
}
if (lhsType.isPrimitive()) {
Class<?> resolvedPrimitive = primitiveWrapperTypeMap.get(rhsType);
return (lhsType == resolvedPrimitive);
} else {
Class<?> resolvedWrapper = primitiveTypeToWrapperMap.get(rhsType);
return (resolvedWrapper != null && lhsType.isAssignableFrom(resolvedWrapper));
}
}
/**
* 如果给定的类是基础类型则返回相应的基础类型的包装器类型
*/
public static Class<?> resolvePrimitiveIfNecessary(Class<?> clazz) {
Assert.notNull(clazz, "Class must not be null");
return (clazz.isPrimitive() && clazz != void.class ? primitiveTypeToWrapperMap.get(clazz) : clazz);
}
/**
* 获取类型全限定名
*/
public static String getQualifiedName(Class<?> clazz) {
Assert.notNull(clazz, "Class must not be null");
return clazz.getTypeName();
}
/**
* 返回源代码中给出的基础类的简单名称。 如果基础类是匿名的,则返回一个空字符串。
* 数组的简单名称是附加“[]”的组件类型的简单名称。 特别是组件类型为匿名的数组的简单名称是“[]”<br/>
* 参考{@link Class#getSimpleName()}
*/
public static String getSimpleName(Class<?> clazz) {
Assert.notNull(clazz, "Class must not be null");
return clazz.getSimpleName();
}
/**
* 返回给定类作为数组实现的所有接口,包括由超类实现的接口。
* 如果类本身是一个接口,它将作为唯一接口返回。
*/
public static Class<?>[] getAllInterfacesForClass(Class<?> clazz) {
return getAllInterfacesForClass(clazz, null);
}
public static Class<?>[] toClassArray(Collection<Class<?>> collection) {
return collection.toArray(new Class<?>[0]);
}
/**
* 返回类加载器一致的给定类作为数组实现的所有接口,包括由超类实现的接口的数组
* 如果类本身是一个接口,它将作为唯一接口数组返回
*/
public static Class<?>[] getAllInterfacesForClass(Class<?> clazz, ClassLoader classLoader) {
return toClassArray(getAllInterfacesForClassAsSet(clazz, classLoader));
}
/**
* 返回类加载器一致的给定类作为数组实现的所有接口,包括由超类实现的接口的Set集合
* 如果类本身是一个接口,它将作为唯一接口数组返回
*/
public static Set<Class<?>> getAllInterfacesForClassAsSet(Class<?> clazz, ClassLoader classLoader) {
Assert.notNull(clazz, "Class must not be null");
if (clazz.isInterface() && isVisible(clazz, classLoader)) {
return Collections.singleton(clazz);
}
Set<Class<?>> interfaces = new LinkedHashSet<>();
Class<?> current = clazz;
while (current != null) {
Class<?>[] ifcs = current.getInterfaces();
for (Class<?> ifc : ifcs) {
if (isVisible(ifc, classLoader)) {
interfaces.add(ifc);
}
}
current = current.getSuperclass();
}
return interfaces;
}
public static boolean isVisible(Class<?> clazz, ClassLoader classLoader) {
if (classLoader == null) {
return true;
}
try {
if (clazz.getClassLoader() == classLoader) {
return true;
}
} catch (SecurityException ex) {
}
return isLoadable(clazz, classLoader);
}
/**
* 确定给定的类是否具有具有给定签名的公共方法,如果可用则返回它(否则返回null )。
* 在指定任何签名的情况下,仅当存在唯一候选时才返回该方法,即具有指定名称的单个公共方法
*
* @param clazz 要分析的clazz
* @param methodName 方法名
* @param paramTypes 方法的参数类型(可以为null)
* @return 方法,如果未找到,则为null
*/
public static Method getMethodIfAvailable(Class<?> clazz, String methodName, Class<?>... paramTypes) {
Assert.notNull(clazz, "Class must not be null");
Assert.notNull(methodName, "Method name must not be null");
if (paramTypes != null) {
try {
return clazz.getMethod(methodName, paramTypes);
} catch (NoSuchMethodException ex) {
return null;
}
} else {
Set<Method> candidates = new HashSet<>(1);
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (methodName.equals(method.getName())) {
candidates.add(method);
}
}
if (candidates.size() == 1) {
return candidates.iterator().next();
}
return null;
}
}
/**
* 返回一个类的公共静态方法
*
* @param clazz 定义方法的类
* @param methodName 静态方法名称
* @param args 方法的参数类型
* @return 静态方法,如果没有找到静态方法,则为{@code null}
* @throws IllegalArgumentException 如果方法名称为空或clazz为空
*/
public static Method getStaticMethod(Class<?> clazz, String methodName, Class<?>... args) {
Assert.notNull(clazz, "Class must not be null");
Assert.notNull(methodName, "Method name must not be null");
try {
Method method = clazz.getMethod(methodName, args);
return Modifier.isStatic(method.getModifiers()) ? method : null;
} catch (NoSuchMethodException ex) {
return null;
}
}
/**
* 确定给定的类是否具有带有给定签名的公共构造函数,并在可用时返回它(否则返回 {@code null})。
*
* @param clazz 分析的clazz
* @param paramTypes 方法的参数类型
* @return 构造函数,或者如果没有找到返回{@code null}
*/
public static <T> Constructor<T> getConstructorIfAvailable(Class<T> clazz, Class<?>... paramTypes) {
Assert.notNull(clazz, "Class must not be null");
try {
return clazz.getConstructor(paramTypes);
} catch (NoSuchMethodException ex) {
return null;
}
}
/**
* 检查给定的类是否可以在给定的 ClassLoader 中加载
*/
private static boolean isLoadable(Class<?> clazz, ClassLoader classLoader) {
try {
return (clazz == classLoader.loadClass(clazz.getName()));
// Else: different class with same name found
} catch (ClassNotFoundException ex) {
// No corresponding class found at all
return false;
}
}
/**
* 确定给定值的类型可以赋值给值分配目标类型
*
* @param type 目标类型
* @param value 应该分配给目标类型的值
*/
public static boolean isAssignableValue(Class<?> type, Object value) {
Assert.notNull(type, "Type must not be null");
return (value != null ? isAssignable(type, value.getClass()) : !type.isPrimitive());
}
}
package com.prowidesoftware.brilliance.util;
import com.prowidesoftware.brilliance.exception.SwiftException;
import org.apache.commons.lang3.time.DateUtils;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class DateUtil {
public static String CURRENT_DATE = "";
public static String defaultFormate = "yyyy-MM-dd HH:mm:ss,SSS"; // 默认的日期格式
/***
* @param paramDate
* 日期
* @param paramInt1
* 0-6 毫秒、秒、分、时、日、月、年
* @param paramInt2
* 增量 为整型
* ***/
public static final Date dateAdd(Date paramDate, int paramInt1, int paramInt2) {
if (paramDate == null)
return null;
Calendar localCalendar = Calendar.getInstance();
localCalendar.setTime(paramDate);
switch (paramInt1) {
case 0:
localCalendar.add(14, paramInt2);
break;
case 1:
localCalendar.add(13, paramInt2);
break;
case 2:
localCalendar.add(12, paramInt2);
break;
case 3:
localCalendar.add(11, paramInt2);
break;
case 4:
localCalendar.add(5, paramInt2);
break;
case 5:
localCalendar.add(2, paramInt2);
break;
case 6:
localCalendar.add(1, paramInt2);
}
return new Date(localCalendar.getTimeInMillis());
}
/**
* 返回一个代表当期日期是星期几的数字。1表示星期天、2表示星期一、7表示星期六
**/
public static int getDayOfWeek(String year, String month, String day) {
Calendar cal = new GregorianCalendar(new Integer(year).intValue(), new Integer(month).intValue() - 1, new Integer(day).intValue());
return cal.get(Calendar.DAY_OF_WEEK);
}
/**
* 当前时间是否符合时间表达式
*
* @param cron
* @return
* @throws ParseException
*/
public static boolean isDateValid(String cron) throws ParseException {
if (StringUtil.isEmpty(cron))
return true;
//CronExpression cronExpression = new CronExpression(cron);
// return cronExpression.isSatisfiedBy(new Date());
return true;
}
/**
* 默认格式格式化当前时间
*
* @return
*/
public static String formatNow() {
return DateUtil.formatNow(defaultFormate);
}
/**
* 按指定格式格式化当前时间
*
* @return
*/
public static String formatNow(String pattern) {
DateFormat dateFormat = new SimpleDateFormat(pattern);
return dateFormat.format(new Date());
}
/**
* 默认格式格式化几分钟后的时间
*
* @param min
* @return
*/
public static String formatMinutesLater(int min) {
Calendar c = Calendar.getInstance();
Date date = new Date();
c.setTime(date);
c.add(Calendar.MINUTE, min);
DateFormat dateFormat = new SimpleDateFormat(defaultFormate);
return dateFormat.format(c.getTime());
}
/**
* 按指定格式格式化几分钟后的时间
*
* @param min
* @return
*/
public static String formatMinutesLater(String pattern, int min) {
Calendar c = Calendar.getInstance();
Date date = new Date();
c.setTime(date);
c.set(Calendar.MINUTE, c.get(Calendar.MINUTE) + min);
DateFormat dateFormat = new SimpleDateFormat(pattern);
return dateFormat.format(c.getTime());
}
/**
* 按默认格式格式化日期
*
* @param date
* @return
*/
public static String format(Date date) {
return DateUtil.format(date, defaultFormate);
}
/**
* 按指定格式格式化日期
*
* @param date
* @return
*/
public static String format(Date date, String pattern) {
DateFormat dateFormat = new SimpleDateFormat(pattern);
if (date != null)
return dateFormat.format(date);
else
return null;
}
/**
* 格式化XML时间为字符串
*
* @param xgc
* @param pattern
* @return
*/
public static String format(XMLGregorianCalendar xgc, String pattern) {
Date date = parseDate(xgc);
return DateUtil.format(date, pattern);
}
/**
* 指定格式的日期转化为XML时间
*
* @param time
* @param pattern
* @return
* @throws ParseException
* @throws DatatypeConfigurationException
*/
public static XMLGregorianCalendar parseXMLGregorianCalendar(String time, String pattern) throws ParseException, DatatypeConfigurationException {
return parseXMLGregorianCalendar(parseDate(time, pattern));
}
/**
* Date转化为XMLGregorianCalendar
*
* @param date
* @return
* @throws ParseException
* @throws DatatypeConfigurationException
*/
public static XMLGregorianCalendar parseXMLGregorianCalendar(Date date) throws ParseException, DatatypeConfigurationException {
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date);
XMLGregorianCalendar xgc = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
return xgc;
}
/**
* 数据库Date类型转化为XML时间
*
* @param date
* @return
* @throws DatatypeConfigurationException
*/
public XMLGregorianCalendar parseXMLGregorianCalendar(java.sql.Date date) throws DatatypeConfigurationException {
GregorianCalendar gc = new GregorianCalendar();
gc.setTimeInMillis(date.getTime());
XMLGregorianCalendar xgc;
xgc = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
return xgc;
}
/**
* 将一个yyyy-MM-dd的时间字符串转化为XMLGregorianCalendar
*
* @param time
* @return
*/
public static XMLGregorianCalendar parseXMLGregorianCalendar(String time) {
XMLGregorianCalendar xgc = null;
try {
xgc = DatatypeFactory.newInstance().newXMLGregorianCalendar();
Date date = DateUtil.parseDate(time.substring(0, 10), "yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(date);
xgc.setYear(c.get(Calendar.YEAR));
xgc.setMonth(c.get(Calendar.MONTH) + 1);
xgc.setDay(c.get(Calendar.DAY_OF_MONTH));
} catch (Exception e) {
throw new SwiftException("00404", "parse date error.", e);
}
return xgc;
}
/**
* XML时间转化为Date
*
* @param xgc
* @return
*/
public static Date parseDate(XMLGregorianCalendar xgc) {
return xgc.toGregorianCalendar().getTime();
}
/**
* 获取两个时间间隔几天
*
* @param fromDate
* @param toDate
* @return
*/
public static int getInterval(Date fromDate, Date toDate) {
long interval = toDate.getTime() - fromDate.getTime();
return (int) (interval / (24 * 3600000));
}
/**
* 获取两个时间的分钟间隔
*
* @param fromDate
* @param toDate
* @return
*/
public static double getIntervalMinutes(Date fromDate, Date toDate) {
long interval = toDate.getTime() - fromDate.getTime();
return NumberUtil.accurateDivide(interval, 60000, 2);
}
/**
* 比较两个时间 如果相等,返回值为0 如果前一个时间比较早,返回值<0 如果前一个时间比较晚,返回值>0
*
* @param firstDate
* @param secondDate
* @return
*/
public static int compareDate(Date firstDate, Date secondDate) {
Calendar firstCalendar = new GregorianCalendar();
firstCalendar.setTime(firstDate);
Calendar secondCalendar = new GregorianCalendar();
secondCalendar.setTime(secondDate);
return firstCalendar.compareTo(secondCalendar);
}
/**
* 字符串转化为Date类型
*
* @param date 日期字符串
* @param parsePattern 日期格式
* @return
* @throws ParseException
*/
public static Date parseDate(String date, String parsePattern) throws ParseException {
return DateUtils.parseDate(date, new String[]{parsePattern});
}
/**
* Date日期格式化之后再次转化为Date(可在需要改变Date携带的信息时使用,如希望把一个
* 'yyyy-MM-dd'的日期变为只有年信息'yyyy'的日期)
*
* @param date
* @param pattern
* @return
* @throws ParseException
*/
public static Date formatAndParseDate(Date date, String pattern) throws ParseException {
String formatDate = DateUtil.format(date, pattern);
return DateUtil.parseDate(formatDate, pattern);
}
/**
* 日期字符串转化为其他日期信息的字符串
*
* @param date
* @param parsePattern
* @param formatPattern
* @return
* @throws ParseException
*/
public static String parseAndFormatDate(String date, String parsePattern, String formatPattern) throws ParseException {
Date parseDate = DateUtils.parseDate(date, new String[]{parsePattern});
return DateUtil.format(parseDate, formatPattern);
}
/**
* 判断两个日期是否在同一天
*
* @param preDate
* @param currDate
* @return
* @throws ParseException
*/
public static boolean checkSameDay(Date preDate, Date currDate) throws ParseException {
if (preDate != null) {
currDate = DateUtil.clearTime(currDate);
preDate = DateUtil.clearTime(preDate);
if (DateUtil.compareDate(preDate, currDate) == 0)
return true;
}
return false;
}
/**
* 去掉日期中的天、分、秒、毫秒信息
*
* @param date
* @return
*/
private static Date clearTime(Date date) {
// 也可以parseandformat的方法实现
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
date = calendar.getTime();
return date;
}
public static Date parseDate(Date date, String parsePattern) throws ParseException {
String dateStr = DateUtil.parseAndFormatDate(DateUtil.format(date), DateUtil.defaultFormate, parsePattern);
Date newDate = DateUtil.parseDate(dateStr, parsePattern);
return newDate;
}
/**
* 获取当前日期
*/
public static Timestamp getTimestamp() {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = null;
try {
d = sf.parse("2010-05-14 00:00:00");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Timestamp timestamp = new Timestamp(d.getTime());
return timestamp;
/*
* Date dNow = new Date(); // 当前时间 Date dBefore = new Date(); Calendar
* calendar = Calendar.getInstance(); // 得到日历 calendar.setTime(dNow);//
* 把当前时间赋给日历 // calendar.add(Calendar.DAY_OF_MONTH, -1); // 设置为前一天
* dBefore = calendar.getTime(); // 得到当前天的时间 Timestamp timestamp = new
* Timestamp(dBefore.getTime()); return timestamp;
*/
}
public static final Timestamp time2(String paramString1, String paramString2) throws ParseException {
return new Timestamp(new SimpleDateFormat(paramString2).parse(paramString1).getTime());
}
// 根据当前日期获取前一天日期
public static String getLastDay(String str, String pattern) throws ParseException {
SimpleDateFormat df = new SimpleDateFormat(pattern);
Date date = df.parse(str);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, -1);
date = calendar.getTime();
return DateUtil.format(date, pattern);
}
}
package com.prowidesoftware.brilliance.util;
import com.prowidesoftware.brilliance.exception.IORuntimeException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.Assert;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class FileUtil {
public static final String CLASSPATH_URL_PREFIX = "classpath:";
public static final String URL_PROTOCOL_FILE = "file";
public static URL getURL(String resourceLocation) {
Assert.notNull(resourceLocation, "Resource location must not be null");
if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length());
ClassLoader cl = ClassUtil.getDefaultClassLoader();
URL url = (cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path));
if (url == null) {
String description = "class path resource [" + path + "]";
throw new IllegalArgumentException(description +
" cannot be resolved to URL because it does not exist");
}
return url;
}
try {
if (isAbsolutePath(resourceLocation)) {
//如果是绝对路径直接返回
return new File(resourceLocation).toURI().toURL();
}
//重复:考虑有的没有加classpath:前缀
ClassLoader cl = ClassUtil.getDefaultClassLoader();
URL url = (cl != null ? cl.getResource(resourceLocation) : ClassLoader.getSystemResource(resourceLocation));
if (url == null) {
//视为url协议
return new URL(resourceLocation);
}
return url;
} catch (MalformedURLException ex) {
// 视为文件路径
try {
return new File(resourceLocation).toURI().toURL();
} catch (MalformedURLException ex2) {
throw new IllegalArgumentException("Resource location [" + resourceLocation +
"] is neither a URL not a well-formed file path");
}
}
}
public static File getFile(String path) {
Assert.notNull(path, "Resource path must not be null");
return getFile(getURL(path));
}
public static File getFile(String rootPath, String childPath) {
Assert.notNull(rootPath, "Resource rootPath must not be null");
Assert.notNull(childPath, "Resource childPath must not be null");
File rootFile = getFile(rootPath);
return new File(rootFile, childPath);
}
public static File getFile(URL resourceUrl) {
Assert.notNull(resourceUrl, "Resource URL must not be null");
if (!URL_PROTOCOL_FILE.equals(resourceUrl.getProtocol())) {
throw new IllegalArgumentException("url cannot be resolved to absolute file path " +
"because it does not reside in the file system: " + resourceUrl);
}
return new File(toURI(resourceUrl).getSchemeSpecificPart());
}
public static URI toURI(URL url) {
return toURI(url.toString());
}
public static URI toURI(String location) {
try {
return new URI(StringUtils.replace(location, " ", "%20"));
} catch (Exception e) {
throw new IllegalArgumentException("URI转换异常:" + e.getMessage(), e);
}
}
public static List<File> loopFiles(File file, FileFilter fileFilter) {
List<File> fileList = new ArrayList();
if (null != file && file.exists()) {
if (file.isDirectory()) {
File[] subFiles = file.listFiles();
if (!ObjectUtil.isEmpty(subFiles)) {
for (int i = 0; i < subFiles.length; ++i) {
File tmp = subFiles[i];
fileList.addAll(loopFiles(tmp, fileFilter));
}
}
} else if (null == fileFilter || fileFilter.accept(file)) {
fileList.add(file);
}
return fileList;
} else {
return fileList;
}
}
/**
* 获取文件或者目录名,如果是文件名则不带扩展名
*/
public static String getFileName(File file) {
if (null == file) {
return null;
} else {
return file.isDirectory() ? file.getName() : preName(file.getName());
}
}
public static String getSuffix(File file) {
if (null == file) {
return null;
} else {
return file.isDirectory() ? null : extName(file.getName());
}
}
public static String extName(String fileName) {
if (fileName == null) {
return null;
} else {
int index = fileName.lastIndexOf(".");
if (index == -1) {
return "";
} else {
String ext = fileName.substring(index + 1);
return StringUtil.containsAny(ext, new char[]{'/', '\\'}) ? "" : ext;
}
}
}
public static String preName(String fileName) {
if (fileName == null) {
return null;
} else {
int index = fileName.lastIndexOf(".");
if (index == -1) {
return "";
} else {
return fileName.substring(0, index);
}
}
}
public static File writeString(String content, String path) {
return writeString(content, path, Charset.defaultCharset());
}
public static File writeString(String content, String path, Charset charset) {
return writeString(content, touch(path), charset, false);
}
public static File writeString(String content, File file, Charset charset, boolean append) {
FileOutputStream out = null;
try {
out = openOutputStream(file, append);
IOUtils.write(content, out, charset);
out.close();
} catch (Exception e) {
throw new IORuntimeException("Write String to File exception",e);
} finally {
IOUtils.closeQuietly(out);
}
return file;
}
public static FileOutputStream openOutputStream(File file, boolean append) {
if (file.exists()) {
if (file.isDirectory()) {
throw new IORuntimeException("File '" + file + "' exists but is a directory");
}
if (!file.canWrite()) {
throw new IORuntimeException("File '" + file + "' cannot be written to");
}
} else {
File parent = file.getParentFile();
if (parent != null && !parent.mkdirs() && !parent.isDirectory()) {
throw new IORuntimeException("Directory '" + parent + "' could not be created");
}
}
try {
return new FileOutputStream(file, append);
} catch (FileNotFoundException e) {
throw new IORuntimeException("File Not Found Exception", e);
}
}
public static File touch(String fullFilePath) {
return fullFilePath == null ? null : touch(getFile(fullFilePath));
}
public static File touch(File file) throws IORuntimeException {
if (null == file) {
return null;
} else {
if (!file.exists()) {
mkParentDirs(file);
try {
file.createNewFile();
} catch (Exception ex) {
throw new IORuntimeException("create new file exception", ex);
}
}
return file;
}
}
public static File mkParentDirs(File file) {
File parentFile = file.getParentFile();
if (null != parentFile && !parentFile.exists()) {
parentFile.mkdirs();
}
return parentFile;
}
public static boolean isAbsolutePath(String path) {
if (StringUtil.isEmpty(path)) {
return false;
} else {
return '/' == path.charAt(0) || path.matches("^[a-zA-Z]:([/\\\\].*)?");
}
}
}
package com.prowidesoftware.brilliance.util;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.FieldPosition;
public class NumberUtil {
public static String decimalFormat(String decimal) {
return NumberUtil.decimalFormat(decimal, 2);
}
public static String decimalFormat(String decimal, int num) {
String string = "#0." + StringUtil.repeat("0", num);
DecimalFormat df = new DecimalFormat(string);
StringBuffer stringBuffer = new StringBuffer("");
df.format(Double.valueOf(decimal), stringBuffer, new FieldPosition(num));
decimal = stringBuffer.toString();
return decimal;
}
public static String decimalFormat(Object decimal, int num) {
String dec = decimal.toString();
return decimalFormat(dec, num);
}
public static String accurateDivide(String dividend, String divisor, int digits) {
BigDecimal decimal = BigDecimal.valueOf(Double.valueOf(dividend));
return decimal.divide(BigDecimal.valueOf(Double.valueOf(divisor)), digits, BigDecimal.ROUND_HALF_UP).toString();
}
public static double accurateDivide(double dividend, double divisor, int digits) {
BigDecimal decimal = BigDecimal.valueOf(dividend);
return decimal.divide(BigDecimal.valueOf(divisor), digits, BigDecimal.ROUND_HALF_UP).doubleValue();
}
public static double round(double v, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
public static int getMax(int[] values) {
if (values != null) {
int max = Integer.MIN_VALUE;
for (int i : values) {
max = max > i ? max : i;
}
return max;
} else {
return -1;
}
}
public static String formatAmt(String amt, int dot) {
String s = NumberUtil.decimalFormat(amt, dot);
return s.replace(".", "");
}
public static String formatAmt(BigDecimal amt, String ccy) {
if (amt == null) {
throw new RuntimeException("Source Amt cannot be null.");
}
int ccyDecimalNum = getCcyDecimalNum(ccy);
String s = NumberUtil.decimalFormat(amt.toString(), ccyDecimalNum);
String pointSuffiex = ".";
for (int i=0; i<ccyDecimalNum; i++) {
pointSuffiex +="0";
}
if (s.indexOf(pointSuffiex) > -1) { //like 1000.00 -> 1000,
return s.replace(pointSuffiex, ",");
} else {
return s.replace(".", ",");//like 1000.01 -> 1000,01
}
}
private static int getCcyDecimalNum(String ccy) {
int decimalNum = 2;
//TODO
return decimalNum;
}
}
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.prowidesoftware.brilliance.util;
import org.springframework.util.Assert;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
public class ObjectUtil {
private static final int INITIAL_HASH = 7;
private static final int MULTIPLIER = 31;
private static final String EMPTY_STRING = "";
private static final String NULL_STRING = "null";
private static final String ARRAY_START = "{";
private static final String ARRAY_END = "}";
private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END;
private static final String ARRAY_ELEMENT_SEPARATOR = ", ";
/**
* 确定给定对象是否为数组:
* 是对象数组或是基元数组。
*
* @param obj 待检查对象
*/
public static boolean isArray(Object obj) {
return (obj != null && obj.getClass().isArray());
}
/**
* 确定给的数组是否为空:
* null和长度为零都表示空。
*
* @param array 待检查数组
*/
public static boolean isEmpty(Object[] array) {
return (array == null || array.length == 0);
}
/**
* 确定下述类型对象是否为空:
* <ul>
* <li>{@code Optional}: considered empty if {@link Optional#isPresent()}</li>
* <li>{@code Array}: considered empty if its length is zero</li>
* <li>{@link CharSequence}: considered empty if its length is zero</li>
* <li>{@link Collection}: considered empty if {@link Collection#isEmpty()}</li>
* <li>{@link Map}: considered empty if {@link Map#isEmpty()}</li>
* </ul>
* <p>如果给定对象为非null且不是上述支持的类型之一,则此方法返回false.</p>
*
* @param obj the object to check
* @return 为空返回true
* @see Optional#isPresent()
* @see ObjectUtil#isEmpty(Object[])
*/
@SuppressWarnings("rawtypes")
public static boolean isEmpty(Object obj) {
if (obj == null) {
return true;
}
if (obj instanceof Optional) {
return !((Optional) obj).isPresent();
}
if (obj instanceof CharSequence) {
return ((CharSequence) obj).length() == 0;
}
if (obj.getClass().isArray()) {
return Array.getLength(obj) == 0;
}
if (obj instanceof Collection) {
return ((Collection) obj).isEmpty();
}
if (obj instanceof Map) {
return ((Map) obj).isEmpty();
}
// else
return false;
}
/**
* 如果对象是Optional则返回其中保存的值;如果Optional是空null;如果对象不是Optional仅仅是返回给定对象的原样
*
* @param obj 待检测对象
* @return 如果对象是Optional则返回其中保存的值;如果Optional是空null;如果对象不是Optional仅仅是返回给定对象的原样
*/
public static Object unwrapOptional(Object obj) {
if (obj instanceof Optional) {
Optional<?> optional = (Optional<?>) obj;
if (!optional.isPresent()) {
return null;
}
Object result = optional.get();
Assert.isTrue(!(result instanceof Optional), "不支持多层Optional使用");
return result;
}
return obj;
}
/**
* 检查给定数组是否包含给定元素
*
* @param array 待检测的数组,如果数组为空,则返回false
* @param element 指定的元素
* @return 是否在给定数组中找到该元素
*/
public static boolean containsElement(Object[] array, Object element) {
if (array == null) {
return false;
}
for (Object arrayEle : array) {
if (nullSafeEquals(arrayEle, element)) {
return true;
}
}
return false;
}
/**
* 将给定对象追加到给定数组,返回一个新数组
* 新数组由输入数组内容加上给定对象组成。
*
* @param array 给定数组,可以为null
* @param obj 待添加的对象
* @return 新数组;如果原数组为null,则返回的新数组只包含当前对象
*/
public static <A, O extends A> A[] addObjectToArray(A[] array, O obj) {
Class<?> compType = Object.class;
if (array != null) {
compType = array.getClass().getComponentType();
} else if (obj != null) {
compType = obj.getClass();
}
int newArrLength = (array != null ? array.length + 1 : 1);
@SuppressWarnings("unchecked")
A[] newArr = (A[]) Array.newInstance(compType, newArrLength);
if (array != null) {
System.arraycopy(array, 0, newArr, 0, array.length);
}
newArr[newArr.length - 1] = obj;
return newArr;
}
/**
* 将给定的数组(可能是原始数组)转换为对象数组(如果需要原始包装对象)。
* null源值将转换为空对象数组。
*
* @param source (可能是原始的)数组
* @return 相应的对象数组(从不为null )
* @throws IllegalArgumentException 如果参数不是数组
*/
public static Object[] toObjectArray(Object source) {
if (source instanceof Object[]) {
return (Object[]) source;
}
if (source == null) {
return new Object[0];
}
if (!source.getClass().isArray()) {
throw new IllegalArgumentException("Source is not an array: " + source);
}
int length = Array.getLength(source);
if (length == 0) {
return new Object[0];
}
Class<?> wrapperType = Array.get(source, 0).getClass();
Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);
for (int i = 0; i < length; i++) {
newArray[i] = Array.get(source, i);
}
return newArray;
}
/**
* 确定给定的对象是否相等,如果两者都为null则返回true ,如果只有一个为null则返回false 。
* 将数组与Arrays.equals进行比较,根据数组元素而不是数组引用执行相等性检查。
*
* @param o1 要比较的第一个对象
* @param o2 要比较的第二个对象
* @return 给定的对象是否相等
* @see Object#equals(Object)
* @see Arrays#equals
*/
public static boolean nullSafeEquals(Object o1, Object o2) {
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
if (o1.equals(o2)) {
return true;
}
if (o1.getClass().isArray() && o2.getClass().isArray()) {
return arrayEquals(o1, o2);
}
return false;
}
/**
* 将数组与Arrays.equals进行比较,根据数组元素而不是数组引用执行相等性检查
*
* @param o1 要比较的第一个数组
* @param o2 要比较的第二个数组
* @return 给定的对象是否相等
* @see #nullSafeEquals(Object, Object)
* @see Arrays#equals
*/
private static boolean arrayEquals(Object o1, Object o2) {
if (o1 instanceof Object[] && o2 instanceof Object[]) {
return Arrays.equals((Object[]) o1, (Object[]) o2);
}
if (o1 instanceof boolean[] && o2 instanceof boolean[]) {
return Arrays.equals((boolean[]) o1, (boolean[]) o2);
}
if (o1 instanceof byte[] && o2 instanceof byte[]) {
return Arrays.equals((byte[]) o1, (byte[]) o2);
}
if (o1 instanceof char[] && o2 instanceof char[]) {
return Arrays.equals((char[]) o1, (char[]) o2);
}
if (o1 instanceof double[] && o2 instanceof double[]) {
return Arrays.equals((double[]) o1, (double[]) o2);
}
if (o1 instanceof float[] && o2 instanceof float[]) {
return Arrays.equals((float[]) o1, (float[]) o2);
}
if (o1 instanceof int[] && o2 instanceof int[]) {
return Arrays.equals((int[]) o1, (int[]) o2);
}
if (o1 instanceof long[] && o2 instanceof long[]) {
return Arrays.equals((long[]) o1, (long[]) o2);
}
if (o1 instanceof short[] && o2 instanceof short[]) {
return Arrays.equals((short[]) o1, (short[]) o2);
}
return false;
}
public static int nullSafeHashCode(Object obj) {
if (obj == null) {
return 0;
}
if (obj.getClass().isArray()) {
if (obj instanceof Object[]) {
return nullSafeHashCode((Object[]) obj);
}
if (obj instanceof boolean[]) {
return nullSafeHashCode((boolean[]) obj);
}
if (obj instanceof byte[]) {
return nullSafeHashCode((byte[]) obj);
}
if (obj instanceof char[]) {
return nullSafeHashCode((char[]) obj);
}
if (obj instanceof double[]) {
return nullSafeHashCode((double[]) obj);
}
if (obj instanceof float[]) {
return nullSafeHashCode((float[]) obj);
}
if (obj instanceof int[]) {
return nullSafeHashCode((int[]) obj);
}
if (obj instanceof long[]) {
return nullSafeHashCode((long[]) obj);
}
if (obj instanceof short[]) {
return nullSafeHashCode((short[]) obj);
}
}
return obj.hashCode();
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(Object[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (Object element : array) {
hash = MULTIPLIER * hash + nullSafeHashCode(element);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(boolean[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (boolean element : array) {
hash = MULTIPLIER * hash + Boolean.hashCode(element);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(byte[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (byte element : array) {
hash = MULTIPLIER * hash + element;
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(char[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (char element : array) {
hash = MULTIPLIER * hash + element;
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(double[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (double element : array) {
hash = MULTIPLIER * hash + Double.hashCode(element);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(float[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (float element : array) {
hash = MULTIPLIER * hash + Float.hashCode(element);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(int[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (int element : array) {
hash = MULTIPLIER * hash + element;
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(long[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (long element : array) {
hash = MULTIPLIER * hash + Long.hashCode(element);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(short[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (short element : array) {
hash = MULTIPLIER * hash + element;
}
return hash;
}
public static boolean isNull(Object obj) {
return null == obj || obj.equals((Object)null);
}
public static boolean isNotNull(Object obj) {
return null != obj && !obj.equals((Object)null);
}
}
package com.prowidesoftware.brilliance.util;
import com.prowidesoftware.brilliance.exception.SwiftException;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* Properties文件工具
*
* @author xiaoyuanzhen
*
*/
public class PropertyUtil {
private static final String XML_FILE_EXTENSION = ".xml";
public static Properties loadProperties(String propertyFile) {
return loadProperties(propertyFile, null);
}
public static Properties loadProperties(String propertyFile, String encode) {
Properties props = new Properties();
try {
fillProperties(props, propertyFile, encode);
} catch (IOException e) {
throw new SwiftException("fill Properties occure exception,filePath=" + propertyFile + ",encode" + encode, e);
}
return props;
}
public static Properties loadProperties(URL url) throws IOException {
Properties props = new Properties();
try (InputStream is =url.openStream()){
if (url.getFile().endsWith(XML_FILE_EXTENSION)) {
props.loadFromXML(is);
} else {
props.load(is);
}
}
return props;
}
static void fillProperties(Properties props, String propertyFile, String encode)
throws IOException {
InputStream is = null;
Reader reader = null;
try {
URL url = FileUtil.getURL(propertyFile);
if (propertyFile.endsWith(XML_FILE_EXTENSION)) {
is = url.openStream();
props.loadFromXML(is);
} else if (encode != null) {
reader = new InputStreamReader(url.openStream(), encode);
props.load(reader);
} else {
is = url.openStream();
props.load(is);
}
} finally {
if (is != null) {
is.close();
}
if (reader != null) {
reader.close();
}
}
}
/**
* 从properties文件中获取指定属性名对应的值
*
* @param propertyFile
* @param propertyName
* @return
*/
private static Map<String, Properties> map = new HashMap<String, Properties>();
public static String getProperty(String propertyFile, String propertyName) {
String propertyValue = "";
InputStream is = null;
try {
Properties propertie = new Properties();
if (!map.containsKey(propertyFile)) {
is = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(propertyFile);
propertie.load(is);
map.put(propertyFile, propertie);
}
propertyValue = map.get(propertyFile).getProperty(propertyName);
} catch (Exception e) {
e.printStackTrace();
propertyValue = "";
} finally {
try {
IOUtils.closeQuietly(is);
} catch (Exception e) {
e.printStackTrace();
}
}
return propertyValue;
}
/**
* 设置properties文件的某个属性值
*
* @param propertyFile
* @param propertyName
* @param propertyValue
* @return
*/
public synchronized static boolean setProperty(String propertyFile, String propertyName,
String propertyValue) {
boolean sav = false;
InputStream is = null;
OutputStream os = null;
try {
Properties propertie = new Properties();
is = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertyFile);
propertie.load(is);
propertie.setProperty(propertyName, propertyValue);
String path = Thread.currentThread().getContextClassLoader().getResource(propertyFile)
.getPath();
os = new FileOutputStream(new File(path));
propertie.store(os, "");
os.flush();
sav = true;
} catch (Exception e) {
e.printStackTrace();
sav = false;
} finally {
try {
is.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return sav;
}
public synchronized static boolean setPropertyValue(String propertyFile, String propertyName,
String propertyValue) {
boolean sav = false;
OutputStream os = null;
InputStream is = null;
try {
Properties propertie = new Properties();
is = new FileInputStream(new File(propertyFile));
propertie.load(is);
propertie.setProperty(propertyName, propertyValue);
os = new FileOutputStream(new File(propertyFile));
propertie.store(os, "");
os.flush();
sav = true;
} catch (Exception e) {
e.printStackTrace();
propertyValue = "";
} finally {
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return sav;
}
private static Properties load(File f, String encoding) throws IOException {
Properties propertie = new Properties();
InputStreamReader is = new InputStreamReader(new FileInputStream(f), encoding);
propertie.load(is);
is.close();
return propertie;
}
private static Properties load(File f) throws IOException {
return load(f, "GBK");
}
public static Properties getProperties(String propertyFile)
throws IOException {
return getProperties(propertyFile,"GBK");
}
public static Properties getProperties(String propertyFile, String encoding)
throws IOException {
return load(new File(propertyFile), encoding);
}
public static String getPropertyValue(String propertyFile, String propertyName) {
String propertyValue = "";
// InputStream is = null;
try {
Properties propertie = load(new File(propertyFile));
propertyValue = propertie.getProperty(propertyName);
} catch (Exception e) {
e.printStackTrace();
propertyValue = "";
}
return propertyValue;
}
}
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.prowidesoftware.brilliance.util;
import com.prowidesoftware.brilliance.exception.InstantiateException;
import com.prowidesoftware.brilliance.spi.ConcurrentReferenceMap;
import org.springframework.util.Assert;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 反射工具
*/
public class ReflectionUtil {
/**
* 预构建的 MethodFilter 匹配所有未在java.lang.Object声明的非桥非合成方法
*/
public static final MethodFilter USER_DECLARED_METHODS =
(method -> !method.isBridge() && !method.isSynthetic());
/**
* 匹配所有非静态、非最终字段的预构建 FieldFilter.
*/
public static final FieldFilter COPYABLE_FIELDS =
(field -> !(Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())));
private static final Method[] EMPTY_METHOD_ARRAY = new Method[0];
private static final Field[] EMPTY_FIELD_ARRAY = new Field[0];
private static final ConcurrentReferenceMap<Class<?>, Method[]> declaredMethodsCache = new ConcurrentReferenceMap<Class<?>, Method[]>(256);
private static final ConcurrentReferenceMap<Class<?>, Field[]> declaredFieldsCache = new ConcurrentReferenceMap<Class<?>, Field[]>(256);
/**
* 获取给定类和参数的可访问构造函数
*
* @param clazz 要检查的 clazz
* @param parameterTypes 所需构造函数的参数类型
* @return 构造函数引用
* @throws NoSuchMethodException 如果不存在这样的构造函数
*/
public static <T> Constructor<T> accessibleConstructor(Class<T> clazz, Class<?>... parameterTypes)
throws NoSuchMethodException {
Constructor<T> ctor = clazz.getDeclaredConstructor(parameterTypes);
makeAccessible(ctor);
return ctor;
}
/**
* 使给定的方法可访问,必要时显式设置它可访问。{@code setAccessible(true)}方法仅在实际需要时调用
*
* @param method 使方法可访问
*/
public static void makeAccessible(Method method) {
if ((!Modifier.isPublic(method.getModifiers()) ||
!Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) {
method.setAccessible(true);
}
}
/**
* 使给定的构造函数可访问,必要时显式设置它可访问。
* setAccessible(true)方法仅在实际需要时调用,以避免与 JVM SecurityManager(如果活动)发生不必要的冲突
*
* @param ctor 使构造函数可访问
*/
public static void makeAccessible(Constructor<?> ctor) {
if ((!Modifier.isPublic(ctor.getModifiers()) ||
!Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) && !ctor.isAccessible()) {
ctor.setAccessible(true);
}
}
/**
* 使给定的字段可访问,必要时明确设置它可访问。
* setAccessible(true)方法仅在实际需要时调用,以避免与 JVM SecurityManager(如果活动)发生不必要的冲突
*
* @param field 使字段可访问
*/
public static void makeAccessible(Field field) {
if ((!Modifier.isPublic(field.getModifiers()) ||
!Modifier.isPublic(field.getDeclaringClass().getModifiers()) ||
Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
field.setAccessible(true);
}
}
/**
* 在给定类中的所有本地声明的字段上调用给定的回调
*
* @param clazz 要分析的目标类
* @param fc 为每个字段调用的回调
*/
public static void doWithLocalFields(Class<?> clazz, FieldCallback fc) {
for (Field field : getDeclaredFields(clazz)) {
try {
fc.doWith(field);
} catch (IllegalAccessException ex) {
throw new IllegalStateException("Not allowed to access field '" + field.getName() + "': " + ex);
}
}
}
/**
* 在目标类中的所有字段上调用给定的回调,沿着类层次结构向上获取所有声明的字段。
*
* @param clazz 要分析的目标类
* @param fc 为每个字段调用的回调
*/
public static void doWithFields(Class<?> clazz, FieldCallback fc) {
doWithFields(clazz, fc, null);
}
/**
* 在目标类中的所有字段上调用给定的回调,沿着类层次结构向上获取所有声明的字段。
*
* @param clazz 要分析的目标类
* @param fc 为每个字段调用的回调
* @param ff 确定要应用回调的字段的过滤器
*/
public static void doWithFields(Class<?> clazz, FieldCallback fc, FieldFilter ff) {
Class<?> targetClass = clazz;
do {
Field[] fields = getDeclaredFields(targetClass);
for (Field field : fields) {
if (ff != null && !ff.matches(field)) {
continue;
}
try {
fc.doWith(field);
} catch (IllegalAccessException ex) {
throw new IllegalStateException("Not allowed to access field '" + field.getName() + "': " + ex);
}
}
targetClass = targetClass.getSuperclass();
}
while (targetClass != null && targetClass != Object.class);
}
/**
* 浅拷贝。给定源对象和目标,它们必须是同一个类或子类,复制所有字段,包括继承的字段。 旨在处理具有公共无参数构造函数的对象
*
* @param src 源对象
* @param dest 目标对象
*/
public static void shallowCopyFieldState(final Object src, final Object dest) {
Assert.notNull(src, "Source for field copy cannot be null");
Assert.notNull(dest, "Destination for field copy cannot be null");
if (!src.getClass().isAssignableFrom(dest.getClass())) {
throw new IllegalArgumentException("Destination class [" + dest.getClass().getName() +
"] must be same or subclass as source class [" + src.getClass().getName() + "]");
}
doWithFields(src.getClass(), field -> {
makeAccessible(field);
Object srcValue = field.get(src);
field.set(dest, srcValue);
}, COPYABLE_FIELDS);
}
/**
* 对给定类的所有匹配方法执行给定的回调操作,如本地声明或等效的(例如给定类实现的基于 Java 8 的接口上的默认方法)。
*
* @param clazz 内省的类
* @param mc 为每个方法调用的回调
*/
public static void doWithLocalMethods(Class<?> clazz, MethodCallback mc) {
Method[] methods = getDeclaredMethods(clazz, false);
for (Method method : methods) {
try {
mc.doWith(method);
} catch (IllegalAccessException ex) {
throw new IllegalStateException("Not allowed to access method '" + method.getName() + "': " + ex);
}
}
}
/**
* 对给定类和超类的所有匹配方法执行给定的回调操作。</br>
* <strong>出现在子类和超类上的相同命名方法将出现两次,除非被ReflectionUtils.MethodFilter排除。</strong>
*
* @param clazz 内省的类
* @param mc 为每个方法调用的回调
*/
public static void doWithMethods(Class<?> clazz, MethodCallback mc) {
doWithMethods(clazz, mc, null);
}
public static void doWithMethods(Class<?> clazz, MethodCallback mc, MethodFilter mf) {
// 继续缓存继承层次结构.
Method[] methods = getDeclaredMethods(clazz, false);
for (Method method : methods) {
if (mf != null && !mf.matches(method)) {
continue;
}
try {
mc.doWith(method);
} catch (IllegalAccessException ex) {
throw new IllegalStateException("Not allowed to access method '" + method.getName() + "': " + ex);
}
}
if (clazz.getSuperclass() != null && (mf != USER_DECLARED_METHODS || clazz.getSuperclass() != Object.class)) {
doWithMethods(clazz.getSuperclass(), mc, mf);
} else if (clazz.isInterface()) {
for (Class<?> superIfc : clazz.getInterfaces()) {
doWithMethods(superIfc, mc, mf);
}
}
}
/**
* 获取子类和所有父类上的所有声明方法。首先包含子类方法。
*
* @param leafClass 要内省的类
*/
public static Method[] getAllDeclaredMethods(Class<?> leafClass) {
final List<Method> methods = new ArrayList<>(20);
doWithMethods(leafClass, methods::add);
return methods.toArray(EMPTY_METHOD_ARRAY);
}
/**
* 获取子类和所有父类的唯一声明方法集。 叶类方法首先被包含在内,在遍历父类层次结构时,任何找到的签名与已包含的方法相匹配的方法都将被过滤掉
*
* @param leafClass 要内省的类
* @return 子类和所有父类的唯一声明方法集
*/
public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) {
return getUniqueDeclaredMethods(leafClass, null);
}
/**
* 获取子类和所有父类的唯一声明方法集。 叶类方法首先被包含在内,在遍历父类层次结构时,任何找到的签名与已包含的方法相匹配的方法都将被过滤掉
*
* @param leafClass 要内省的类
* @param mf 确定要考虑的方法的过滤器
* @return 子类和所有父类的唯一声明方法集
*/
public static Method[] getUniqueDeclaredMethods(Class<?> leafClass, MethodFilter mf) {
final List<Method> methods = new ArrayList<>(20);
doWithMethods(leafClass, method -> {
boolean knownSignature = false;
Method methodBeingOverriddenWithCovariantReturnType = null;
for (Method existingMethod : methods) {
if (method.getName().equals(existingMethod.getName()) &&
method.getParameterCount() == existingMethod.getParameterCount() &&
Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) {
// 如果新发现的方法返回类型是已存在方法的子类型,则覆盖
if (existingMethod.getReturnType() != method.getReturnType() &&
existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) {
methodBeingOverriddenWithCovariantReturnType = existingMethod;
} else {
knownSignature = true;
}
break;
}
}
if (methodBeingOverriddenWithCovariantReturnType != null) {
methods.remove(methodBeingOverriddenWithCovariantReturnType);
}
if (!knownSignature) {
methods.add(method);
}
}, mf);
return methods.toArray(EMPTY_METHOD_ARRAY);
}
/**
* Class.getDeclaredMethods()的变体,它使用本地缓存以避免 JVM 的 SecurityManager 检查和新的 Method 实例。
* 此外,它还包括来自本地实现的接口的 Java 8 默认方法,因为这些方法实际上被视为已声明的方法。
*
* @param clazz 内省的类
* @return 缓存的方法数组
*/
public static Method[] getDeclaredMethods(Class<?> clazz) {
return getDeclaredMethods(clazz, true);
}
/**
* 针对不带参数的提供的目标对象调用指定的Method 。 调用静态Method时,目标对象可以为null
*
* @param method 要调用的方法
* @param target 调用方法的目标对象
* @param args 调用方法的参数
* @return 调用结果,如果有的话
*/
public static Object invokeMethod(Method method, Object target, Object... args) {
try {
return method.invoke(target, args);
} catch (Exception ex) {
handleReflectionException(ex);
}
throw new IllegalStateException("代码不应该执行到这!!!");
}
public static void handleReflectionException(Exception ex) {
if (ex instanceof NoSuchMethodException) {
throw new IllegalStateException("Method not found: " + ex.getMessage());
}
if (ex instanceof IllegalAccessException) {
throw new IllegalStateException("Could not access method or field: " + ex.getMessage());
}
if (ex instanceof InvocationTargetException) {
handleInvocationTargetException((InvocationTargetException) ex);
}
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
throw new UndeclaredThrowableException(ex);
}
public static void handleInvocationTargetException(InvocationTargetException exs) {
Throwable ex = exs.getTargetException();
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
if (ex instanceof Error) {
throw (Error) ex;
}
throw new UndeclaredThrowableException(ex);
}
/**
* 试图找到一个Method上与提供的名称和任何参数提供的类。 搜索直到Object所有超类。
* 如果找不到Method则返回null
*
* @param clazz 内省的类
* @param name 方法的名称
* @return Method 对象,如果没有找到则为null
*/
public static Method findMethod(Class<?> clazz, String name) {
return findMethod(clazz, name, new Class<?>[0]);
}
/**
* 尝试使用提供的名称和参数类型在提供的类上查找Method 。 搜索直到Object所有超类。
* 如果找不到Method则返回null
*
* @param clazz 内省的类
* @param name 方法的名称
* @param paramTypes 方法的参数类型(可以为null以指示任何签名)
* @return Method 对象,如果没有找到则为null
*/
public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) {
Assert.notNull(clazz, "Class must not be null");
Assert.notNull(name, "Method name must not be null");
Class<?> searchType = clazz;
while (searchType != null) {
Method[] methods = (searchType.isInterface() ? searchType.getMethods() : getDeclaredMethods(searchType));
for (Method method : methods) {
if (name.equals(method.getName()) &&
(paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) {
return method;
}
}
searchType = searchType.getSuperclass();
}
return null;
}
private static Field[] getDeclaredFields(Class<?> clazz) {
Assert.notNull(clazz, "Class must not be null");
Field[] result = declaredFieldsCache.get(clazz);
if (result == null) {
try {
result = clazz.getDeclaredFields();
declaredFieldsCache.put(clazz, (result.length == 0 ? EMPTY_FIELD_ARRAY : result));
} catch (Throwable ex) {
throw new IllegalStateException("Failed to introspect Class [" + clazz.getName() +
"] from ClassLoader [" + clazz.getClassLoader() + "]", ex);
}
}
return result;
}
private static Method[] getDeclaredMethods(Class<?> clazz, boolean defensive) {
Assert.notNull(clazz, "Class must not be null");
Method[] result = declaredMethodsCache.get(clazz);
if (result == null) {
try {
Method[] declaredMethods = clazz.getDeclaredMethods();
List<Method> defaultMethods = findConcreteMethodsOnInterfaces(clazz);
if (defaultMethods != null) {
result = new Method[declaredMethods.length + defaultMethods.size()];
System.arraycopy(declaredMethods, 0, result, 0, declaredMethods.length);
int index = declaredMethods.length;
for (Method defaultMethod : defaultMethods) {
result[index] = defaultMethod;
index++;
}
} else {
result = declaredMethods;
}
declaredMethodsCache.put(clazz, (result.length == 0 ? EMPTY_METHOD_ARRAY : result));
} catch (Throwable ex) {
throw new IllegalStateException("Failed to introspect Class [" + clazz.getName() +
"] from ClassLoader [" + clazz.getClassLoader() + "]", ex);
}
}
return (result.length == 0 || !defensive) ? result : result.clone();
}
private static List<Method> findConcreteMethodsOnInterfaces(Class<?> clazz) {
List<Method> result = null;
for (Class<?> ifc : clazz.getInterfaces()) {
for (Method ifcMethod : ifc.getMethods()) {
if (!Modifier.isAbstract(ifcMethod.getModifiers())) {
if (result == null) {
result = new ArrayList<>();
}
result.add(ifcMethod);
}
}
}
return result;
}
public static <T> T instantiateClass(Constructor<T> ctor, Object... args) {
Assert.notNull(ctor, "Constructor must not be null");
try {
ReflectionUtil.makeAccessible(ctor);
return ctor.newInstance(args);
} catch (InstantiationException ex) {
throw new InstantiateException(ctor, "Is it an abstract class?", ex);
} catch (IllegalAccessException ex) {
throw new InstantiateException(ctor, "Is the constructor accessible?", ex);
} catch (IllegalArgumentException ex) {
throw new InstantiateException(ctor, "Illegal arguments for constructor", ex);
} catch (InvocationTargetException ex) {
throw new InstantiateException(ctor, "Constructor threw exception", ex.getTargetException());
}
}
@FunctionalInterface
public interface FieldCallback {
/**
* 使用给定字段执行操作.
*
* @param field 待操作的字段
*/
void doWith(Field field) throws IllegalArgumentException, IllegalAccessException;
}
@FunctionalInterface
public interface MethodCallback {
/**
* Perform an operation using the given method.
*
* @param method the method to operate on
*/
void doWith(Method method) throws IllegalArgumentException, IllegalAccessException;
}
@FunctionalInterface
public interface MethodFilter {
/**
* 确定给定的方法是否匹配.
*
* @param method 检查的方法
*/
boolean matches(Method method);
/**
* 基于此过滤器和提供的过滤器创建一个复合过滤器。如果此过滤器不匹配,则不会应用下一个过滤器。
* <p>如果此过滤器不匹配,则不会应用下一个过滤器。
*
* @param next 下一个MethodFilter
* @return 复合MethodFilter
* @throws IllegalArgumentException 如果 MethodFilter 参数为null
*/
default MethodFilter and(MethodFilter next) {
Assert.notNull(next, "Next MethodFilter must not be null");
return method -> matches(method) && next.matches(method);
}
}
@FunctionalInterface
public interface FieldFilter {
/**
* 确定给定的字段是否匹配。
*
* @param field 待检测字段
*/
boolean matches(Field field);
/**
* 基于此过滤器和提供的过滤器创建一个复合过滤器。如果此过滤器不匹配,则不会应用下一个过滤器。
*
* @param next 下一个FieldFilter
* @return 复合FieldFilter
* @throws IllegalArgumentException 如果 FieldFilter 参数为null
*/
default FieldFilter and(FieldFilter next) {
Assert.notNull(next, "Next FieldFilter must not be null");
return field -> matches(field) && next.matches(field);
}
}
}
package com.prowidesoftware.brilliance.util;
import com.prowidesoftware.brilliance.constants.Mx2MtConstants;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 字符串处理工具类
*
* @author xiaoyuanzhen
*/
public abstract class StringUtil {
public static boolean hasLength(String str) {
return (str != null && !str.isEmpty());
}
public static boolean containsAny(String str, char... testChars) {
if (!isEmpty(str)) {
int len = str.length();
for (int i = 0; i < len; ++i) {
if (ArrayUtil.contains(testChars, str.charAt(i))) {
return true;
}
}
}
return false;
}
/**
* 文件流转换成String字符串
*
* @throws IOException
**/
public static String toString(String path, String charset) throws IOException {
FileInputStream fis = new FileInputStream(new File(path));
String s = IOUtils.toString(fis);
fis.close();
return s;
}
/**
* 替换最后一处字符串,此方法如果目标代码中出现特殊字符,会导致正则无法使用
*
* @param str
* @param dest
* @param replacement
* @return
*/
@Deprecated
public static String replaceLast(String str, String dest, String replacement) {
return str.replaceAll(dest + "(?!.*" + dest + ".*)", replacement);
}
/**
* 判断是否为空
**/
public static boolean isEmpty(String content) {
if (content != null && !content.trim().equals(""))
return false;
else
return true;
}
/*
* public static String getDocKey(String formatpath) { String str[] =
* formatpath.split("\\/"); int len = str.length - 1; String s = str[len];
* int length = s.length() - 4; s = s.substring(0, length); return s; }
*/
public static String repeat(String sc, int num) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < num; i++)
sb.append(sc);
return sb.toString();
}
/**
* 主要是解决在利用split分隔的时候,结尾如果为空,split分隔的数组将会忽略空串的问题
*
* @param regex
* @param s
* @return by hujun on 2013/10/12
*/
public static String[] split(String regex, String s) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
int index = 0;
while (m.find()) {
index++;
}
return s.split(regex, index + 1);
}
/**
* 分析使用","分隔的多个参数,类似函数的参数分析器
*
* @param str 如:"abc,2,'cd'"
* @return
*/
public static String[] analyseArgs(String str) {
int len = str.length();
boolean inStr = false;
List<String> args = new ArrayList<String>();
StringBuffer tmpArg = new StringBuffer();
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
if (c == ' ') {
if (inStr)
tmpArg.append(c);
} else if (c == '\'') {
inStr = !inStr;
tmpArg.append(c);
} else if (c == ',') {
if (inStr)
tmpArg.append(c);
else {
args.add(tmpArg.toString());
tmpArg = new StringBuffer();
}
} else
tmpArg.append(c);
}
String lastStr = tmpArg.toString();
if (!lastStr.equals(""))
args.add(lastStr);
return args.toArray(new String[args.size()]);
}
/**
* @param db
* @pattern 模式
**/
public static String formatDouble(double db, String pattern) {
DecimalFormat df = new DecimalFormat(pattern);
return df.format(db);
}
public static String formatDouble(double db) {
String str = (db + "").toLowerCase();
int index;
if ((index = str.indexOf('e')) != -1) {
int len = Integer.parseInt(str.substring(index + 1));
int dotIndex = str.indexOf('.');
int lackLen = len - (index - dotIndex - 1);
if (len > 0) {
if (lackLen > 0) {
return String.format("%.0f", db);
}
return str.substring(0, dotIndex) + str.substring(dotIndex + 1, dotIndex + len + 1) + "." + str.substring(dotIndex + len + 1, index);
} else {
return String.format("%." + (-lackLen) + "f", db);
}
} else
return str;
}
public static String getFillChars(String str, String leftchars, String chars, String direct, int totalLen) {
int left = totalLen - str.length();
if (left > 0) {
for (int i = 0; i < left; i++) {
leftchars = leftchars + chars;
}
}
if (direct.toLowerCase().equals("left")) {
return leftchars + str;
} else {
return str + leftchars;
}
}
public static String convertRightToLeftSlash(String content) {
return content.replaceAll("\\\\", "/");// 用四个反斜杠来代替一个反斜杠
}
public static byte[] getBytes(String srcStr, String encoding) throws UnsupportedEncodingException {
return srcStr.getBytes(encoding);
}
public static String bytesToString(byte[] bytes, String encoding) throws UnsupportedEncodingException {
return new String(bytes, encoding);
}
public static String bytesToString(byte[] bytes) {
return new String(bytes);
}
public static byte[] getBytes(String srcStr) {
return srcStr.getBytes();
}
/**
* 按照num指定的长度创建一个由数字组成的随机字符串
*
* @param num
* @return
*/
public static String createRandomNumStr(int num) {
String str = String.format("%." + num + "f", Math.random());
return str.substring(2);
}
public static void main(String[] args) {
System.out.println(fillWithChar("1", "0", "left", 2));
}
/***
* 字符串填充
*
* @param obj
* 源数据 可以为String,doule(doule为两位小数类型),int
* @param chars
* 填充字符
* @param totalLen
* 包括left right两种情况
* **/
public static String fillWithChar(Object obj, String chars, String direct, int totalLen) {
String leftchars = "";
if (obj instanceof String) {
String str = (String) obj;
return StringUtil.getFillChars(str, leftchars, chars, direct, totalLen);
} else if (obj instanceof Integer) {
String str = String.valueOf(obj);
return getFillChars(str, leftchars, chars, direct, totalLen);
} else if (obj instanceof Long) {
String str = String.valueOf(obj);
return getFillChars(str, leftchars, chars, direct, totalLen);
} else if (obj instanceof Double) {
Double d = (Double) obj;
double dd = d.doubleValue();
String str = StringUtil.formatDouble(dd);
str = str.replace(".", "");
return getFillChars(str, leftchars, chars, direct, totalLen);
} else if (obj instanceof BigDecimal) {
BigDecimal b = (BigDecimal) obj;
DecimalFormat df = new DecimalFormat();
String st = df.format(b);
return StringUtil.getFillChars(st, leftchars, chars, direct, totalLen);
} else {
return null;
}
}
public static double round(double v, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
// 转化字符串为十六进制编码
public static String toHexString(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s4 = Integer.toHexString(ch);
str = str + s4;
}
return str;
}
public static List<String> match(String pattern, String target) {
Pattern p = Pattern.compile(pattern, Pattern.DOTALL | Pattern.MULTILINE);
Matcher matcher = p.matcher(target);
List<String> groupsa = new ArrayList<String>();
while (matcher.find()) {
String paramName = matcher.group();
groupsa.add(paramName);
}
return groupsa;
}
/**
* <p>
* <b>此函数在顺德项目中使用</b>
* </p>
**/
public static boolean isNotEmpty(String content) {
return !isEmpty(content);
}
/**
* <p>
* <b>此函数在顺德项目中使用</b>
* </p>
*
* @param str 原始字符串
* @param subLen 子字符串长长度
* @param num 切分个数
* @return 分割后的子字符串数组
* @throws UnsupportedEncodingException
*/
public static String[] divideGBKStr(String str, int subLen, int num) throws UnsupportedEncodingException {
str = str.replace("\r", "").replace("\n", "").trim();
byte[] strBytes = str.getBytes("GBK");
String[] strs = new String[num];
int byteStartIdx = 0;
int strStartIdx = 0;
for (int i = 0; i < num; i++) {
int copyLen = strBytes.length - byteStartIdx >= subLen ? subLen : strBytes.length - byteStartIdx;
if (copyLen <= 0)
strs[i] = " ";
else {
byte[] subBytes = new byte[copyLen];
System.arraycopy(strBytes, byteStartIdx, subBytes, 0, copyLen);
String subStr = new String(subBytes, "GBK");
int subStrLen = subStr.length();
int subStrOfStrLen = str.substring(strStartIdx, strStartIdx + subStrLen).getBytes("GBK").length;
if (subStrOfStrLen > subLen) {
subBytes = new byte[copyLen - 1];
System.arraycopy(strBytes, byteStartIdx, subBytes, 0, copyLen - 1);
byteStartIdx += copyLen - 1;
strStartIdx += subStrLen - 1;
} else {
byteStartIdx += copyLen;
strStartIdx += subStrLen;
}
strs[i] = new String(subBytes, "GBK");
}
}
return strs;
}
/**
* 返回一个代表当期日期是星期几的数字。1表示星期天、2表示星期一、7表示星期六
**/
public static int getDayOfWeek(String year, String month, String day) {
Calendar cal = new GregorianCalendar(new Integer(year).intValue(), new Integer(month).intValue() - 1, new Integer(day).intValue());
return cal.get(Calendar.DAY_OF_WEEK);
}
public static String toASCII(String str) {
char[] chars = str.toCharArray(); // 把字符中转换为字符数组
String asciiString = "";
for (int i = 0; i < chars.length; i++) {// 输出结果
asciiString = asciiString + Integer.toString((int) chars[i]);
}
return asciiString;
}
/**
* 到固定长度换行
*
* @param length 每行的长度
* @param rows 最多行数
* @param string 需换行的字符串
* @return
* @throws Exception
*/
public static String getStringByEnter(String string, int length, int rows) throws Exception {
if (StringUtils.isEmpty(string))
return string;
if (--rows <= 0) {
return string.length() > length ? string.substring(0, length) : string;
}
if (string.length() > length) {
return string.substring(0, length) + Mx2MtConstants.NEW_LINE +
getStringByEnter(string.substring(length), length, rows);
}
return string;
}
public static String ASCIItoString(String str) {
char a = (char) Integer.parseInt(str);
return String.valueOf(a);
}
}
package com.prowidesoftware.brilliance.util;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.util.GregorianCalendar;
public class SwiftTransferUtil {
public static XMLGregorianCalendar getXMLGregorianCalendarNow() {
GregorianCalendar gregorianCalendar = new GregorianCalendar();
DatatypeFactory datatypeFactory = null;
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
XMLGregorianCalendar now = datatypeFactory.newXMLGregorianCalendar(gregorianCalendar);
return now;
}
}
package com.prowidesoftware.brilliance.util;
import com.prowidesoftware.brilliance.constants.ERROR;
import com.prowidesoftware.brilliance.exception.SwiftException;
import org.apache.commons.io.FileUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 通过模型类将模板转成字符串
*
* **/
public class TemplateUtil {
/**
* 通过模型生成函数将模板转成字符串
* @Param String template 模板名称
* @Param cache 模板变量Map集合
* @Param outPut 文件输出保存路径
* @Param encode 文件生成编码
* @Return string 返回生成的文件字符串
* **/
public static String makeFileByTemplate(String template, Map<String, Object> cache, String outPut, String encode) {
String lastStr="";
ClassLoader classLoader = TemplateUtil.class.getClassLoader();
URL url = classLoader.getResource("template/");
if (url != null) {
VelocityEngine ve = new VelocityEngine();
try {
ve.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, url.toURI().getPath());
ve.setProperty(Velocity.OUTPUT_ENCODING, encode);
ve.setProperty(Velocity.INPUT_ENCODING, encode);
ve.init();
VelocityContext context = new VelocityContext();
Template vt = ve.getTemplate(template);
context.put("vm", cache);
StringWriter sw = new StringWriter();
vt.merge(context, sw);
lastStr=sw.toString();
if (!StringUtil.isEmpty(outPut)) {
FileUtils.write(new File(outPut),lastStr.replaceAll("\\\\\\\\", "\\$"), encode, false);
}
} catch (Exception e) {
throw new SwiftException(ERROR.ERROR_0002,ERROR.ERROR_0002_DESC);
}
} else {
}
return lastStr;
}
public static void makeFileByTemplate2(String template, Map<String, Object> cache, String outPut, String encode) throws IOException {
ClassLoader classLoader = TemplateUtil.class.getClassLoader();
URL url = classLoader.getResource("template/");
if (url != null) {
VelocityEngine ve = new VelocityEngine();
ve.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, url.getPath());
ve.setProperty(Velocity.OUTPUT_ENCODING, encode);
ve.setProperty(Velocity.INPUT_ENCODING, encode);
ve.init();
VelocityContext context = new VelocityContext();
Template vt = ve.getTemplate(template);
for (String key : cache.keySet()) {
context.put(key, cache.get(key));
}
StringWriter sw = new StringWriter();
vt.merge(context, sw);
FileUtils.write(new File(outPut), sw.toString().replaceAll("\\\\\\\\", "\\$"), encode, false);
} else {
throw new FileNotFoundException("没有在template目录下找到模板文件:" + template);
}
}
public static void main(String[] args) throws Exception {
Map map = new HashMap();
List<List> list = new ArrayList<List>();
List<String> subList = new ArrayList<String>();
subList.add("aaa");
subList.add("bbb");
list.add(subList);
subList = new ArrayList<String>();
subList.add("ccc");
subList.add("ddd");
subList.add("eee");
list.add(subList);
map.put("digestValue", "abc");
map.put("data", list);
makeFileByTemplate("singlewindow.vm", map, "d:/test.xml", "utf-8");
}
}
package com.prowidesoftware.brilliance.util;
import com.prowidesoftware.brilliance.constants.ERROR;
import com.prowidesoftware.brilliance.exception.SwiftException;
import java.net.URL;
public class UrlUtil {
public static URL getCommonURL(String relativePath) {
URL url = Thread.currentThread().getContextClassLoader().getResource(relativePath);
if (url == null) {
url = UrlUtil.class.getClassLoader().getResource(relativePath);
if (url == null) {
url = UrlUtil.class.getClassLoader().getResource("");
try {
return new URL(url + relativePath);
} catch (Exception e) {
throw new SwiftException(ERROR.ERROR_0003,ERROR.ERROR_0003_DESC);
}
}
}
return url;
}
}
/*
* Copyright 2006-2021 Prowide
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.prowidesoftware.deprecation;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Map;
import java.util.logging.Level;
/**
* Helper API to implement the http://www.prowidesoftware.com/resources/deprecation-policy
*
* @author sebastian
* @since 7.8.9
*/
public class DeprecationUtils {
/**
* Environment variable used to switch off deprecation phase implementation
*/
public static final String PW_DEPRECATED = "PW_DEPRECATED";
private static final transient java.util.logging.Logger log = java.util.logging.Logger.getLogger(DeprecationUtils.class.getName());
// Suppress default constructor for noninstantiability
private DeprecationUtils() {
throw new AssertionError();
}
/**
* According to the deprecation policy this method implements the phase 2 which
* involves logging a warning and making a small pause in the execution thread.
*
* @param message the log message
*/
@SuppressWarnings("rawtypes")
public static void phase2(final Class clazz, final String method, final String message) {
if (!isSet(EnvironmentVariableKey.NOLOG)) {
log.warning(notice(clazz, method) + message);
}
if (!isSet(EnvironmentVariableKey.NODELAY)) {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.log(Level.WARNING, notice(clazz, method) + message, e);
}
}
}
@SuppressWarnings("rawtypes")
private static String notice(final Class clazz, final String method) {
StringBuilder note = new StringBuilder();
note.append("The API ").append(clazz.getSimpleName());
if (method != null) {
note.append("#").append(method);
}
note.append(" is deprecated. ");
return note.toString();
}
/**
* According to the deprecation policy this method implements the phase 3 which
* involves throwing a runtime exception.
*
* @param message the log message
*/
@SuppressWarnings("rawtypes")
public static void phase3(final Class clazz, final String method, final String message) {
if (!isSet(EnvironmentVariableKey.NOEXCEPTION)) {
throw new UnsupportedOperationException(notice(clazz, method) + message);
} else {
/*
* fall back to phase 2
*/
phase2(clazz, method, message);
}
}
/**
* Returns true if the environment variable {@link #PW_DEPRECATED} contains
* the given key in its value
*/
private static final boolean isSet(final EnvironmentVariableKey key) {
return StringUtils.containsIgnoreCase(System.getenv(PW_DEPRECATED), key.name());
}
/**
* Helper hack to set the environment variable from Java.
*
* <p>For example if all keys are passed as parameter, this will set
* the environment variable PW_DEPRECATED=nolog,nodelay,noexception
*
* @param keys the variables to set in the environment variable
*/
public static void setEnv(EnvironmentVariableKey... keys) {
if (keys != null && keys.length > 0) {
StringBuilder value = new StringBuilder();
for (EnvironmentVariableKey key : keys) {
if (value.length() > 0) {
value.append(",");
}
value.append(key.name().toLowerCase());
}
setEnv(PW_DEPRECATED, value.toString());
}
}
/**
* Sets the environment variable PW_DEPRECATED to an empty string, meaning
* all flags corresponding to the deprecation phase will be active by default.
*/
public static void clearEnv() {
setEnv(PW_DEPRECATED, "");
}
/**
* Helper hack to set environment variables from Java code
*/
@SuppressWarnings({"unchecked", "rawtypes"})
private static void setEnv(final String key, final String value) {
try {
Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
theEnvironmentField.setAccessible(true);
Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
env.put(key, value);
Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
theCaseInsensitiveEnvironmentField.setAccessible(true);
Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
cienv.put(key, value);
} catch (NoSuchFieldException e) {
try {
Class[] classes = Collections.class.getDeclaredClasses();
Map<String, String> env = System.getenv();
for (Class cl : classes) {
if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
Field field = cl.getDeclaredField("m");
field.setAccessible(true);
Object obj = field.get(env);
Map<String, String> map = (Map<String, String>) obj;
map.clear();
map.put(key, value);
}
}
} catch (Exception e2) {
e2.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
/**
* Keywords for the environment variable {@link #PW_DEPRECATED}
*/
public enum EnvironmentVariableKey {
NOLOG,
NODELAY,
NOEXCEPTION
}
}
/*
* Copyright 2006-2021 Prowide
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.prowidesoftware.deprecation;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Main annotation to track prowide deprecated items.
* <p>
* See <a href="http://www.prowidesoftware.com/resources/deprecation-policy">Deprecation Policy</a>
* for more details.
*
* <p>This annotation is intended for internal use of Prowide and
* source code administration. It may suffer incompatible changes
* without prior notice.
*
* @author miguel
* @since 7.8.1
*/
@Retention(RetentionPolicy.SOURCE)
@Documented
public @interface ProwideDeprecated {
String comment() default "";
/**
* Scheduled year for entering phase 2 of deprecation
*/
TargetYear phase2() default TargetYear.SRU2021;
/**
* Scheduled year for entering phase 3 of deprecation
*/
TargetYear phase3() default TargetYear.SRU2022;
/**
* Scheduled year for entering phase 4 of deprecation
*/
TargetYear phase4() default TargetYear.SRU2023;
}
/*
* Copyright 2006-2021 Prowide
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.prowidesoftware.deprecation;
/**
* Target year for which a deprecation operation is scheduled.
* Mainly used for tracking items in codebase.
*
* @author miguel
* @since 7.8.1
*/
public enum TargetYear {
SRU2021,
SRU2022,
SRU2023
}
/*
* Copyright 2006-2021 Prowide
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Classes to support Prowide deprecation policy: <a href="http://www.prowidesoftware.com/resources/deprecation-policy">Deprecation Policy</a>
*/
package com.prowidesoftware.deprecation;
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment