This commit is contained in:
Rinjae
2025-09-05 18:37:58 +09:00
commit c3e2de482b
331 changed files with 76984 additions and 0 deletions
@@ -0,0 +1,16 @@
package com.eactive.eai.transformer;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
@SuppressWarnings("resource")
static public void main(String[] args) throws Exception {
new ClassPathXmlApplicationContext(
new String[] {
"com/eactive/eai/transformer/springconfig-jetty6.xml",
"com/eactive/eai/transformer/springconfig-transformer.xml",
});
}
}
@@ -0,0 +1,99 @@
package com.eactive.eai.transformer;
public class SystemKeys {
public static final String TRANSFROMER_BYTESMESSAGE_CHARSET = "transformer.bytesmessage.charset";
public static final String TRANSFROMER_BYTESMESSAGE_CHARSET_DEFAULT = "utf-8";
public static final String TRANSFROMER_STRING_TRIMEND = "transformer.string.trimend";
public static final String TRANSFROMER_VALIDATION = "transformer.validation";
public static final String TRANSFROMER_DECIMALPOINT_ADD = "transformer.decimalpoint.add";
public static final String TRANSFROMER_LAYOUT_CACHE_INIT_ONSTARTUP = "transformer.layout.cache.init.onstartup";
public static final String TRANSFROMER_LAYOUT_CACHE_SIZE = "transformer.layout.cache.size";
public static final String TRANSFROMER_LAYOUT_CACHE_IDLE_SEC = "transformer.layout.cache.idle.sec";
public static final String TRANSFROMER_LAYOUT_PERMCACHE_SIZE = "transformer.layout.permcache.size";
public static final String TRANSFROMER_PARSER_CACHE_SIZE = "transformer.parser.cache.size";
public static final String LAYOUT_CACHE_SIZE_DEFAULT = "400";
public static final String LAYOUT_PERMCACHE_SIZE_DEFAULT = "200";
public static final String LAYOUT_CACHE_IDLE_DEFAULT = "3600"; // 1시간
public static final String TRANSFROMER_PARSER_CACHE_DEFAULT = "10000";
public static final String TRANSFROMER_XML_CACHE_SIZE = "transformer.xml.cache.size";
public static final String TRANSFROMER_XML_CACHE_IDLE_SEC = "transformer.xml.cache.idle.sec";
public static final String XML_CACHE_SIZE_DEFAULT = "4000";
public static final String XML_CACHE_IDLE_DEFAULT = "3600"; // 1시간
private static String bytesMessageCharset = TRANSFROMER_BYTESMESSAGE_CHARSET_DEFAULT;
private static boolean stringTrimEnd = true;
private static boolean validationEnabled = true;
private static boolean addDecimalpoint = false;
private static boolean layoutCacheOnStartup = false;
static {
reload();
}
private SystemKeys() {
}
public static void reload() {
// BytesMessage에 대한 cahrset
bytesMessageCharset = System.getProperty(TRANSFROMER_BYTESMESSAGE_CHARSET, TRANSFROMER_BYTESMESSAGE_CHARSET_DEFAULT);
String sBoolean = System.getProperty(TRANSFROMER_STRING_TRIMEND, "true");
try {
stringTrimEnd = Boolean.valueOf(sBoolean);
} catch (Exception ex) {
stringTrimEnd = true;
}
sBoolean = System.getProperty(TRANSFROMER_VALIDATION, "true");
try {
validationEnabled = Boolean.valueOf(sBoolean);
} catch (Exception ex) {
validationEnabled = true;
}
sBoolean = System.getProperty(TRANSFROMER_DECIMALPOINT_ADD, "false");
try {
addDecimalpoint = Boolean.valueOf(sBoolean);
} catch (Exception ex) {
addDecimalpoint = false;
}
sBoolean = System.getProperty(TRANSFROMER_LAYOUT_CACHE_INIT_ONSTARTUP, "false");
try {
layoutCacheOnStartup = Boolean.valueOf(sBoolean);
} catch (Exception ex) {
layoutCacheOnStartup = false;
}
}
public static String getBytesMessageCharset() {
return bytesMessageCharset;
}
public static void setBytesMessageCharset(String bytesMessageCharset) {
SystemKeys.bytesMessageCharset = bytesMessageCharset;
}
public static boolean isStringTrimEnd() {
return stringTrimEnd;
}
public static boolean isValidationEnabled() {
return validationEnabled;
}
public static boolean isAddDecimalPointEnabled() {
return addDecimalpoint;
}
public static boolean isLayoutCacheOnStartup() {
return layoutCacheOnStartup;
}
}
@@ -0,0 +1,357 @@
package com.eactive.eai.transformer;
import java.util.Iterator;
import com.eactive.eai.transformer.engine.TransformEngine;
import com.eactive.eai.transformer.engine.TransformException;
import com.eactive.eai.transformer.engine.TransformResult;
import com.eactive.eai.transformer.engine.Transformer;
import com.eactive.eai.transformer.layout.Item;
import com.eactive.eai.transformer.layout.Layout;
import com.eactive.eai.transformer.layout.LayoutManager;
import com.eactive.eai.transformer.layout.LayoutTypeKey;
import com.eactive.eai.transformer.message.Message;
import com.eactive.eai.transformer.message.MessageFactory;
import com.eactive.eai.transformer.message.XMLMessage;
import com.eactive.eai.transformer.transform.Transform;
import com.eactive.eai.transformer.transform.TransformManager;
import com.eactive.eai.transformer.util.Logger;
import com.eactive.eai.transformer.util.MemoryLogger;
import com.eactive.eai.transformer.util.XmlUtil;
public class TransformService {
protected static Logger logger = Logger.getLogger("transformer");
private TransformService() {
}
@SuppressWarnings("unchecked")
public static Object transform(String infoKey, boolean isReq, String transformName, Object[] sources, boolean isMass) throws java.lang.Exception {
Transform transform = null;
Message[] sourceMessages = null;
Message targetMessage = null;
try {
if (transformName == null)
throw new RuntimeException("전문레이아웃매핑(변환)이름을 정의하지 않았습니다. - " + transformName);
if (sources == null)
throw new RuntimeException("전문레이아웃매핑(변환) 소스 데이터가 NULL 입니다.");
TransformEngine engine = TransformEngine.getInstance();
Transformer transformer = engine.getTransformer();
sourceMessages = new Message[sources.length];
TransformManager manager = TransformManager.getManager();
transform = manager.getTransform(transformName);
if (transform == null) {
throw new Exception("전문레이아웃매핑(변환)정보를 찾을 수 없음 - " + transformName);
}
for (int i = 0; i < sources.length; i++) {
Layout l = null;
try {
l = transform.getSourceLayout(i);
}
catch(Exception ex) {
throw new Exception("전문레이아웃매핑(변환) 중 변환등록오류 - 소스레이아웃 미등록");
}
if(l == null || l.getName() == null || l.getName().length() == 0) {
throw new Exception("전문레이아웃매핑(변환) 중 소스레이아웃 생성 오류 - 변환정보에 소스레이아웃 명이 없음");
}
try {
sourceMessages[i] = MessageFactory.getFactory().getMessage(l.getName());
String sourceType = l.getLayoutType().getName();
if(LayoutTypeKey.JSON.equals(sourceType)) {
// sourceMessages[i].setData((String) sources[i]);
// FIX-ME : Socket으로 JSON이 송수신되는 경우, json bytes가 올 수 있음
String jsonString = "";
if (sources[i] instanceof byte[]) {
jsonString = new String((byte[]) sources[i]);
} else {
jsonString = (String) sources[i];
}
sourceMessages[i].setData(jsonString);
}
else if(LayoutTypeKey.XML.equals(sourceType)) {
String xmlString = "";
if (sources[i] instanceof byte[]) {
xmlString = new String((byte[]) sources[i]);
} else {
xmlString = (String) sources[i];
}
String rootItemName = ((XMLMessage) sourceMessages[i]).getLayout().getRootItem().getName();
// 비표준 XML의 경우를 고려하여 XML Header 제거 후 Root 추가
String xmlAddString = "";
xmlString = XmlUtil.removeXMLHeader(xmlString);
xmlAddString = "<" + rootItemName + ">" + xmlString + "</" + rootItemName + ">";
sourceMessages[i].setData(xmlAddString);
}
// else if (LayoutTypeKey.BYTES.equals(sourceType) || LayoutTypeKey.EBCDIC.equals(sourceType)) {
// sourceMessages[i].setData(sources[i]);
// }
else {
sourceMessages[i].setData(sources[i]);
}
} catch (Exception e) {
throw new TransformerException("전문레이아웃매핑(변환) 중 소스레이아웃 생성 오류 - ", e);
}
}
try {
Object resultObj =null;
if (isMass){
Layout t = transform.getTargetLayout();
targetMessage = MessageFactory.getFactory().getMessage(t.getName());
//참조정보 제거
for (Iterator<Item> iter = targetMessage.fullIterator(); iter.hasNext(); ) {
Item x = iter.next();
if (x.getOccRef() !=null && x.getOccRef().trim().length() > 0 ){
x.setOccRef("");
logger.info(infoKey+"] Mass 거래 OccRef 제거 target "+ x.getPathName());
}
}
TransformResult result = transformer.transform(transformName, targetMessage, sourceMessages, null);
resultObj = result.getResultMessage().getData();
}else{
targetMessage = transformer.transform(transformName, sourceMessages);
resultObj = targetMessage.getData();
}
/**
* memory logging
*/
memoryLog(infoKey, isReq, transformName, sourceMessages, targetMessage);
String targetType = transform.getTargetLayout().getLayoutType().getName();
if(LayoutTypeKey.XML.equals(targetType)) {
String resultXml = (String) resultObj;
String rootItemName = ((XMLMessage) targetMessage).getLayout().getRootItem().getName();
return removeXMLRootItem(resultXml, rootItemName);
} else {
return resultObj;
}
} catch (Exception e) {
throw new TransformException("전문레이아웃매핑(변환) 중 오류 - " + transformName,
transformName,
targetMessage,
sourceMessages,
null,
e);
}
} catch (Exception e) {
logger.error(getErrorSummary(transform, sourceMessages, targetMessage, e, false), e);
MemoryLogger.error(getErrorSummary(transform, sourceMessages, targetMessage, e, true), e);
throw e;
}
}
private static String removeXMLRootItem(String xmlString, String rootItemName) {
String prefix = "<" + rootItemName + ">";
String suffix = "</" + rootItemName + ">";
int s_idx = xmlString.indexOf(prefix);
int e_idx = xmlString.indexOf(suffix);
if (s_idx == -1 || e_idx == -1) {
return xmlString;
} else {
return xmlString.substring(s_idx + prefix.length(), e_idx);
}
}
public static Object transformSingle(String infoKey, boolean isReq, String transformName,
Object sources) throws java.lang.Exception {
return transform(infoKey, isReq, transformName, new Object[] { sources },false);
}
public static Object transformComp(String infoKey, boolean isReq, String transformName,
Object[] sources, String[] layoutNames) throws Exception {
Transform transform = null;
Message[] sourceMessages = null;
Message targetMessage = null;
try {
if (transformName == null)
throw new RuntimeException("전문레이아웃매핑(변환)이름을 정의하지 않았습니다. - "
+ transformName);
if (sources == null)
throw new RuntimeException("전문레이아웃매핑(변환) 소스 데이터가 NULL 입니다.");
if (layoutNames == null)
throw new RuntimeException("복합 거래의 결과 레이아웃이 NULL 입니다.");
TransformEngine engine = TransformEngine.getInstance();
Transformer transformer = engine.getTransformer();
sourceMessages = new Message[sources.length];
TransformManager manager = TransformManager.getManager();
transform = manager.getTransform(transformName);
if (transform == null) {
throw new Exception("전문레이아웃매핑(변환)규칙을 찾을 수 없습니다. - " + transformName);
}
boolean exsist = false;
// 전문레이아웃매핑(변환)규칙의 소스 레이아웃 정보안에 파라미터로 받은 레이아웃이 있는지 확인함
for (int i = 0; i < layoutNames.length; i++) {
if (layoutNames[i] != null) {
exsist = false;
for (int j = 0; j < transform.getSourceLayoutCount(); j++) {
Layout layout = transform.getSourceLayout(j);
if (layout != null
&& layoutNames[i].equals(layout.getName())) {
exsist = true;
break;
}
}
if (!exsist) {
throw new RuntimeException(transformName
+ " 전문레이아웃매핑(변환)규칙에서 복합거래의 결과 레이아웃 [" + layoutNames[i] + "] 이 존재하지 않습니다.");
}
}
}
for (int i = 0; i < layoutNames.length; i++) {
Layout l = null;
try {
l = LayoutManager.getManager().getLayoutByName(layoutNames[i]);
if (l != null)
sourceMessages[i] = MessageFactory.getFactory().getMessage(l.getName());
if (l != null && sources[i] != null) {
String sourceType = l.getLayoutType().getName();
if (LayoutTypeKey.XML.equals(sourceType)) {
String xmlString = null;
if (sources[i] instanceof byte[]) {
xmlString = new String((byte[]) sources[i]);
} else {
xmlString = (String) sources[i];
}
String rootItemName = ((XMLMessage) sourceMessages[i]).getLayout()
.getRootItem().getName();
xmlString = XmlUtil.removeXMLHeader(xmlString);
xmlString = "<" + rootItemName + ">" + xmlString + "</" + rootItemName + ">";
sourceMessages[i].setData(xmlString);
}
else if (LayoutTypeKey.JSON.equals(sourceType)) {
sourceMessages[i].setData((String) sources[i]);
}
// else if (LayoutTypeKey.BYTES.equals(sourceType) || LayoutTypeKey.EBCDIC.equals(sourceType)) {
// sourceMessages[i].setData(sources[i]);
// }
else {
sourceMessages[i].setData(sources[i]);
}
}
} catch (Exception e) {
throw new TransformerException("전문레이아웃매핑(변환) 소스 레이아웃을 생성할 수 없습니다", e);
}
}
try {
targetMessage = transformer.transform(transformName, sourceMessages);
Object resultObj = targetMessage.getData();
/**
* memory logging
*/
memoryLog(infoKey, isReq, transformName, sourceMessages, targetMessage);
String targetType = transform.getTargetLayout().getLayoutType().getName();
// if (targetType.equals("XML") || targetType.equals("UXML")) {
if (LayoutTypeKey.XML.equals(targetType)) {
String resultXml = (String) resultObj;
String rootItemName = ((XMLMessage) targetMessage).getLayout().getRootItem().getName();
return removeXMLRootItem(resultXml, rootItemName);
} else {
return resultObj;
}
} catch (Exception e) {
throw new TransformException("전문레이아웃매핑(변환) 중 오류 - " + transformName,
transformName,
targetMessage,
sourceMessages,
null,
e);
}
} catch (Exception e) {
logger.error(getErrorSummary(transform, sourceMessages, targetMessage, e, false), e);
MemoryLogger.error(getErrorSummary(transform, sourceMessages, targetMessage, e, true), e);
throw e;
}
}
private static String getErrorSummary(Transform transform, Message[] sourceMessages, Message targetMessage, Exception exception, boolean isHtml) {
StringBuilder sb = new StringBuilder();
sb.append("전문레이아웃매핑(변환) 중 오류 - " + exception.getMessage());
try {
if (transform != null) {
sb.append("transform=");
if (isHtml)
sb.append("<a href='/transform/" + transform.getName() + "'>");
sb.append(transform.getName());
if (isHtml)
sb.append("</a>");
}
if (sourceMessages != null) {
sb.append(", sources=(");
for (int i=0; i<sourceMessages.length; i++) {
if (sourceMessages[i] == null)
continue;
if (i>0)
sb.append(",");
if (isHtml)
sb.append("<a href='/message/" + sourceMessages[i].getName() + "'>");
sb.append(sourceMessages[i].getName());
if (isHtml)
sb.append("</a>");
}
sb.append(")");
}
if (targetMessage != null && transform != null && transform.getTargetLayout() != null) {
if (isHtml)
sb.append("<a href='/message/" + transform.getTargetLayout().getName() + "'>");
sb.append(", target=(" + transform.getTargetLayout().getName() + ")");
if (isHtml)
sb.append("</a>");
}
sb.append("\n");
return sb.toString();
} catch(Exception e) {
logger.warn(e.getMessage(), e);
return sb.toString();
}
}
private static void memoryLog(String infoKey, boolean isReq, String transformName,
Message[] sources, Message target) {
if (!MemoryLogger.isMemoryLogEnabled()) return;
try {
StringBuilder sb = new StringBuilder();
sb.append(String.format("infoKey=%s, %-5s, transformName=%s\n",
(infoKey==null ? "" : infoKey.trim()),
isReq ? "REQ" : "RES",
transformName));
sb.append("<b>transform = " + transformName + "</b>\n");
sb.append(TransformManager.getManager().getTransform(transformName).toString());
for (int i=0; i<sources.length; i++) {
sb.append("\n<b>sources[" + i + "] = " + sources[i].getName() + "</b>");
sb.append("\n" + sources[i].toString());
}
sb.append("\n<b>target = " + target.getName() + "</b>");
sb.append("\n" + target.toString());
MemoryLogger.txlog(sb.toString());
} catch(Exception e) {
logger.error(transformName + " | " + e.getMessage(), e);
}
}
}
@@ -0,0 +1,18 @@
package com.eactive.eai.transformer;
public class TransformerException extends RuntimeException {
private static final long serialVersionUID = 1L;
public TransformerException(String message) {
super(message);
}
public TransformerException(Throwable cause) {
super(cause);
}
public TransformerException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,9 @@
package com.eactive.eai.transformer.dao;
import java.util.Map;
public interface DaoInterface<D> {
public Map<String, D> load();
}
@@ -0,0 +1,13 @@
package com.eactive.eai.transformer.dao;
import java.util.Map;
import com.eactive.eai.transformer.function.FunctionDefinition;
public interface FunctionDao extends DaoInterface<FunctionDefinition> {
FunctionDefinition findFunctionByName(String functionName);
Map<String, FunctionDefinition> load();
}
@@ -0,0 +1,16 @@
package com.eactive.eai.transformer.dao;
import java.util.Map;
import com.eactive.eai.transformer.layout.Item;
import com.eactive.eai.transformer.layout.Layout;
public interface LayoutDao extends DaoInterface<Layout> {
Map<String, Layout> load();
Item findItemByName(String layoutName);
Layout findLayoutByName(String layoutName);
Map<String, String> findPermanent();
}
@@ -0,0 +1,14 @@
package com.eactive.eai.transformer.dao;
import java.util.Map;
import com.eactive.eai.transformer.layout.LayoutType;
public interface LayoutTypeDao extends DaoInterface<LayoutType> {
Map<String, LayoutType> load();
LayoutType findLayoutTypeByName(String typeName);
}
@@ -0,0 +1,18 @@
package com.eactive.eai.transformer.dao;
import java.io.Serializable;
public class LoadingUnit implements Serializable {
private static final long serialVersionUID = 1L;
boolean overwrite = false;
public boolean getOverwrite() {
return overwrite;
}
public void setOverwrite(boolean overwrite) {
this.overwrite = overwrite;
}
}
@@ -0,0 +1,13 @@
package com.eactive.eai.transformer.dao;
import java.util.Map;
import com.eactive.eai.transformer.transform.Transform;
public interface TransformDao extends DaoInterface<Transform> {
Map<String, Transform> load();
Transform findTransformByName(String transformName);
}
@@ -0,0 +1,16 @@
package com.eactive.eai.transformer.dao;
import com.eactive.eai.transformer.TransformerException;
public class TransformerDaoException extends TransformerException {
private static final long serialVersionUID = 1L;
public TransformerDaoException(String message) {
super(message);
}
public TransformerDaoException(String message, Throwable t) {
super(message, t);
}
}
@@ -0,0 +1,51 @@
package com.eactive.eai.transformer.dao.excel;
public class ArraySheet implements Sheet {
String[][] cells;
public ArraySheet(int row, int col) {
cells = new String[row][col];
}
public void setString(int row, int col, String value) {
cells[row][col] = value;
}
public String getCellString(int row, int col) throws Exception {
return cells[row][col];
}
public int getCellInt(int row, int col) throws Exception {
return Integer.parseInt(cells[row][col]);
}
public boolean existsRow(int row) throws Exception {
return cells.length > row;
}
public boolean existsCell(int row, int col) throws Exception {
if (!existsRow(row))
return false;
return cells[row].length > col;
}
public boolean isEquals(int row, int col, String value) throws Exception {
if (value == null)
return false;
return value.equals(cells[row][col]);
}
public String getCellValue(int row, int col) {
return cells[row][col];
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i=0; i<cells.length; i++) {
for (int j=0; j<cells[i].length; j++) {
sb.append("sheet[" + i + "][" + j + "] : " + cells[i][j] + "\n");
}
}
return sb.toString();
}
}
@@ -0,0 +1,94 @@
package com.eactive.eai.transformer.dao.excel;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.TreeMap;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.transformer.dao.TransformerDaoException;
public abstract class BaseExcelDao<K, V> {
protected static Logger logger = Logger.getLogger("transformer.dao");
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
private String baseDir;
protected BaseExcelDao(String baseDir) {
String rootDir = System.getProperty("transformer.rule.dir", "");
if ("".equals(rootDir)) {
rootDir = ".";
}
this.baseDir = rootDir + File.separator + baseDir;
}
public Map<K, V> load() {
if (logger.isInfoEnabled()) {
logger.info(getClass().getSimpleName() + " | loading dir - " + baseDir);
}
try {
Map<K, V> map = new TreeMap<>();
File dir = new File(baseDir);
File[] files = dir.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].isFile() && files[i].getName().toLowerCase().endsWith(".xls")) {
map.putAll(loadExcelFile(files[i].getPath()));
}
}
}
return map;
} catch (Exception e) {
throw new TransformerDaoException(e.getMessage(), e);
}
}
protected Map<K, V> loadExcelFile(String fileName) {
File file = new File(fileName);
if (file.getName().startsWith("-")) {
return new TreeMap<>();
}
try (InputStream in = new BufferedInputStream(new FileInputStream(fileName))) {
/**
* find sheets
*/
Sheet[] sheets = null;
sheets = ExcelSheet.getExcelSheets(in);
/**
* type & version
*/
String type = sheets[0].getCellString(2, 2);
String version = sheets[0].getCellString(3, 2);
boolean overwrite = sheets[0].isEquals(6, 4, "O");
if (logger.isDebugEnabled()) {
String msg = String.format(" - %-25s | %1s, %-10s | %s", "loading excel - " + type, version,
(overwrite ? "overwrite" : ""), file.getName());
logger.debug(msg);
}
return loadSheets(sheets);
} catch (Exception e) {
throw new TransformerDaoException("error when load excel file '" + fileName + "'", e);
}
}
public String getCurrentDateTime() {
return DATE_FORMAT.format(ZonedDateTime.now());
}
abstract protected Map<K, V> loadSheets(Sheet[] sheets) throws Exception;
abstract protected Map<K, V> removeSheets(Sheet[] sheets) throws Exception;
abstract protected Map<K, V> parse(Sheet[] sheets) throws Exception;
}
@@ -0,0 +1,137 @@
package com.eactive.eai.transformer.dao.excel;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.eactive.eai.common.util.Logger;
public class ExcelSheet implements Sheet {
protected static Logger logger = Logger.getLogger("transformer.dao");
private HSSFSheet sheet;
private ExcelSheet(HSSFWorkbook workbook, int sheetIndex) {
this.sheet = workbook.getSheetAt(sheetIndex);
}
public static ExcelSheet[] getExcelSheets(InputStream in) throws Exception {
HSSFWorkbook workbook = new HSSFWorkbook(in);
ExcelSheet[] sheets = new ExcelSheet[workbook.getNumberOfSheets()];
for (int i = 0; i < sheets.length; i++) {
sheets[i] = new ExcelSheet(workbook, i);
}
return sheets;
}
public String getCellString(int row, int column) throws Exception {
HSSFRow hrow = sheet.getRow(row);
if (hrow == null) {
throw new Exception("cannt read excel file line number : " + (row + 1));
}
HSSFCell cell = hrow.getCell((short) column);
if (cell == null) {
return "";
}
try {
if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
return "" + ((int) cell.getNumericCellValue());
} else {
if (cell.getStringCellValue() == null) {
return "";
}
return cell.getStringCellValue().trim();
}
} catch(Exception e) {
throw new Exception("getCellString(" + (row+1) + "," + column + ") operation failed", e);
}
}
@SuppressWarnings("deprecation")
public int getCellInt(int row, int column) throws Exception {
HSSFCell cell = sheet.getRow(row).getCell((short) column);
try {
if (cell==null) {
throw new Exception("getCellInt(" + row + "," + column + ") operation failed - cell value is null");
}
if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
return (int) cell.getNumericCellValue();
} else {
return Integer.parseInt(cell.getStringCellValue().trim());
}
} catch(Exception e) {
throw new Exception("getCellInt(" + (row+1) + "," + column + ") operation failed", e);
}
}
public boolean existsRow(int row) throws Exception {
boolean isExist = true;
if( row > sheet.getLastRowNum()
|| this.getCellValue(row, 0) == null
|| getCellValue(row, 1) == null) {
isExist = false;
}
return isExist;
}
public boolean existsCell(int row, int col) throws Exception {
boolean isExist = true;
if (!existsRow(row) || this.getCellValue(row, col) == null)
isExist = false;
return isExist;
}
public boolean isEquals(int row, int column, String value) throws Exception {
return getCellString(row, column).equals(value);
}
public String getCellValue(int row, int column) {
HSSFRow hrow = sheet.getRow(row);
if (hrow == null)
return null;
HSSFCell cell = hrow.getCell((short) column);
if (cell == null)
return null;
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_BLANK:
return "";
case HSSFCell.CELL_TYPE_BOOLEAN:
return Boolean.toString(cell.getBooleanCellValue());
case HSSFCell.CELL_TYPE_ERROR:
return Byte.toString(cell.getErrorCellValue());
case HSSFCell.CELL_TYPE_FORMULA:
return cell.getCellFormula();
case HSSFCell.CELL_TYPE_NUMERIC:
return Double.toString(cell.getNumericCellValue());
case HSSFCell.CELL_TYPE_STRING:
return cell.getStringCellValue();
default :
return null;
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i=0; i<sheet.getLastRowNum(); i++) {
if (sheet.getRow(i) != null && sheet.getRow(i).getCell(0) != null)
sb.append("sheet[" + i + "] : " + sheet.getRow(i).getCell(0).getStringCellValue() + "\n");
}
return sb.toString();
}
}
@@ -0,0 +1,148 @@
package com.eactive.eai.transformer.dao.excel;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.eactive.eai.data.entity.onl.transformer.function.Function;
import com.eactive.eai.transformer.dao.TransformerDaoException;
import com.eactive.eai.transformer.function.FunctionDefinition;
import com.eactive.eai.transformer.function.ParameterDefinition;
import com.eactive.eai.transformer.function.loader.FunctionLoader;
import com.eactive.eai.transformer.function.mapper.FunctionMapper;
import com.eactive.eai.transformer.util.ConstantUtil;
@Service
public class FunctionExcelDao extends BaseExcelDao<String, FunctionDefinition> {
@Autowired
private FunctionLoader functionLoader;
private static final int DATA_ROW_OFFSET = 10;
private static final int COL_FUNC_NAME = 1;
private static final int COL_FUNC_DESC = 2;
private static final int COL_RETN_TYPE = 3;
private static final int COL_FUNC_TYPE = 4;
private static final int COL_FUNC_CLAS = 5;
private static final int COL_PARA_NAME = 6;
private static final int COL_PARA_DESC = 7;
private static final int COL_PARA_TYPE = 8;
@Autowired
private FunctionMapper functionMapper;
public FunctionExcelDao() {
super("function");
}
protected Map<String, FunctionDefinition> parse(Sheet[] sheets) {
Sheet sheet = sheets[0];
Map<String, FunctionDefinition> map = new TreeMap<>();
int pc = 1;
FunctionDefinition fd = null;
ParameterDefinition pd = null;
try {
for (int currentRow = DATA_ROW_OFFSET; sheet.existsRow(currentRow); currentRow++) {
try {
String funcName = sheet.getCellString(currentRow, COL_FUNC_NAME);
String paraName = sheet.getCellString(currentRow, COL_PARA_NAME);
if (funcName.trim().length() > 0) {
fd = new FunctionDefinition();
fd.setName(funcName);
fd.setDescription(sheet.getCellString(currentRow, COL_FUNC_DESC));
fd.setReturnTypeId(
ConstantUtil.getDataTypeId(sheet.getCellString(currentRow, COL_RETN_TYPE), ""));
fd.setFunctionTypeId(
ConstantUtil.getFunctionTypeId(sheet.getCellString(currentRow, COL_FUNC_TYPE)));
fd.setFunctionClass(sheet.getCellString(currentRow, COL_FUNC_CLAS));
/**
* set overwrite
*/
boolean overwrite = sheet.isEquals(6, 4, "O");
fd.setOverwrite(overwrite);
map.put(fd.getName(), fd);
pc = 1;
if (paraName.trim().length() > 0) {
pd = new ParameterDefinition();
pd.setFunctionName(fd.getName());
pd.setName(sheet.getCellString(currentRow, COL_PARA_NAME));
pd.setDescription(sheet.getCellString(currentRow, COL_PARA_DESC));
pd.setTypeId(
ConstantUtil.getDataTypeId(sheet.getCellString(currentRow, COL_PARA_TYPE), ""));
pd.setSeqNo(pc++);
fd.addParameter(pd);
}
} else if (fd != null && paraName.trim().length() > 0) {
pd = new ParameterDefinition();
pd.setFunctionName(fd.getName());
pd.setName(sheet.getCellString(currentRow, COL_PARA_NAME));
pd.setDescription(sheet.getCellString(currentRow, COL_PARA_DESC));
pd.setTypeId(ConstantUtil.getDataTypeId(sheet.getCellString(currentRow, COL_PARA_TYPE), ""));
pd.setSeqNo(pc++);
fd.addParameter(pd);
} else {
break;
}
} catch (Exception e) {
logger.error("[ERROR] !!!!! " + e.getMessage() + " - ROW: " + currentRow, e);
}
}
} catch (Exception e) {
throw new TransformerDaoException(e.getMessage(), e);
}
return map;
}
public FunctionDefinition findFunctionByName(String functionName) {
return null;
}
protected Map<String, FunctionDefinition> loadSheets(Sheet[] sheets) {
Map<String, FunctionDefinition> map = parse(sheets);
return map;
}
protected Map<String, FunctionDefinition> removeSheets(Sheet[] sheets) {
List<Function> functions = functionLoader.findAll();
int functionSize = functions.size();
functionLoader.deleteAll(functions);
if (logger.isInfoEnabled()) {
logger.info("" + functionSize + " 개의 FunctionDefinition 데이터를 삭제했습니다.");
}
return null;
}
public void save(Map<String, FunctionDefinition> functionMap) {
if (logger.isInfoEnabled()) {
logger.info(" + save functions");
}
for (Iterator<FunctionDefinition> fitr = functionMap.values().iterator(); fitr.hasNext();) {
FunctionDefinition fd = fitr.next();
if (fd.getOverwrite()) {
functionLoader.findById(fd.getName())
.ifPresent(function -> functionLoader.delete(function));
}
Function function = functionMapper.toEntity(fd);
functionLoader.save(function);
}
}
}
@@ -0,0 +1,703 @@
package com.eactive.eai.transformer.dao.excel;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.eactive.eai.transformer.dao.TransformerDaoException;
import com.eactive.eai.transformer.layout.Item;
import com.eactive.eai.transformer.layout.ItemFactory;
import com.eactive.eai.transformer.layout.Layout;
import com.eactive.eai.transformer.layout.LayoutType;
import com.eactive.eai.transformer.layout.LayoutTypeManager;
import com.eactive.eai.transformer.layout.LayoutValidator;
import com.eactive.eai.transformer.layout.Types;
import com.eactive.eai.transformer.message.Message;
import com.eactive.eai.transformer.message.MessageFactory;
import com.eactive.eai.transformer.util.ConstantUtil;
@Service
public class Layout2ExcelDao extends BaseExcelDao<String, Layout> {
private static String COL_REGEXP_LAYOUT_DESC;
private int COL_LAYOUT_DESC;
private static String COL_REGEXP_NO;
private int COL_NO;
private static String COL_REGEXP_DESC;
private int COL_DESC;
private static String COL_REGEXP_DPTH;
private int COL_DPTH;
private static String COL_REGEXP_NODE;
private int COL_NODE;
private static String COL_REGEXP_OCC_TYPE;
private int COL_OCC_TYPE;
private static String COL_REGEXP_OCC_REF;
private int COL_OCC_REF;
private static String COL_REGEXP_TYPE;
private int COL_TYPE;
private static String COL_REGEXP_LEN;
private int COL_LEN;
private static String COL_REGEXP_DEC_POINT_LEN;
private int COL_DEC_POINT_LEN; // 소숫점길이
private static String COL_REGEXP_CODE;
private int COL_CODE;
private static String COL_REGEXP_NAME;
private int COL_NAME;
private static int COL_BASE; // EAI(...) 라고 표시된 컬럼
private static String COL_REGEXP_START_FLAG;
private static String COL_REGEXP_MATCH_FLAG;
private static String COL_REGEXP_NOTE;
private int COL_NOTE;
private int COL_DEFAULT; // EAI초기값
private int COL_CHANGE_BASE;
private String SHEET_NAME;
@Autowired
protected LayoutTypeManager layoutTypeManager;
public Layout2ExcelDao() {
super("layout2");
LayoutExcelLoadFormatManager manager = LayoutExcelLoadFormatManager.getInstance();
COL_REGEXP_LAYOUT_DESC = manager.getData("COL_REGEXP_LAYOUT_DESC");// 인터페이스명
COL_REGEXP_NO = manager.getData("COL_REGEXP_NO");// 일련번호
COL_REGEXP_DESC = manager.getData("COL_REGEXP_DESC");// 한글명
COL_REGEXP_DPTH = manager.getData("COL_REGEXP_DPTH");// 깊이
COL_REGEXP_NODE = manager.getData("COL_REGEXP_NODE");// 항목편진구분코드(GROUP/FIELD/ARRAY)
COL_REGEXP_OCC_TYPE = manager.getData("COL_REGEXP_OCC_TYPE");// 배열최대갯수
COL_REGEXP_OCC_REF = manager.getData("COL_REGEXP_OCC_REF");// 반복횟수참조정보
COL_REGEXP_TYPE = manager.getData("COL_REGEXP_TYPE");// 테이터타입(String/Long/BigDecimal)
COL_REGEXP_LEN = manager.getData("COL_REGEXP_LEN");// 데이터길이
COL_REGEXP_DEC_POINT_LEN = manager.getData("COL_REGEXP_DEC_POINT_LEN");// 소숫점길이
COL_REGEXP_CODE = manager.getData("COL_REGEXP_CODE");// 코드변환
COL_REGEXP_NAME = manager.getData("COL_REGEXP_NAME");// 영문명
COL_REGEXP_NOTE = manager.getData("COL_REGEXP_NOTE");// 비고
COL_REGEXP_START_FLAG = manager.getData("COL_REGEXP_START_FLAG");
COL_REGEXP_MATCH_FLAG = manager.getData("COL_REGEXP_MATCH_FLAG");
COL_LAYOUT_DESC = manager.getInt("COL_LAYOUT_DESC");// 인터페이스명
COL_NO = manager.getInt("COL_NO");// 일련번호
COL_DESC = manager.getInt("COL_DESC");// 한글명
COL_DPTH = manager.getInt("COL_DPTH");// 깊이
COL_NODE = manager.getInt("COL_NODE");// 항목편진구분코드(GROUP/FIELD/ARRAY)
COL_OCC_TYPE = manager.getInt("COL_OCC_TYPE");// 배열최대갯수
COL_OCC_REF = manager.getInt("COL_OCC_REF");// 반복횟수참조정보
COL_TYPE = manager.getInt("COL_TYPE");// 테이터타입(String/Long/BigDecimal)
COL_LEN = manager.getInt("COL_LEN");// 데이터길이
COL_DEC_POINT_LEN = manager.getInt("COL_DEC_POINT_LEN");// 소숫점길이
COL_CODE = manager.getInt("COL_CODE");// 코드변환
COL_NAME = manager.getInt("COL_NAME");// 영문명
COL_NOTE = manager.getInt("COL_NOTE");// 비고
COL_NOTE = manager.getInt("COL_DEFAULT");// 비고
COL_BASE = manager.getInt("COL_BASE");// 베이스
SHEET_NAME = manager.getData("SHEET_NAME");// sheet명
}
protected Map<String, Layout> loadExcelFile(String filename) {
File file = new File(filename);
if (file.getName().startsWith("-")) {
return new TreeMap<>();
}
InputStream in = null;
try {
/**
* find sheets
*/
in = new BufferedInputStream(new FileInputStream(filename));
ExcelSheet[] sheets = null;
try {
sheets = ExcelSheet.getExcelSheets(in);
} catch (Exception e) {
throw new Exception("sheets 를 얻어낼 수 없읍니다. - '" + filename + "'", e);
}
if (logger.isDebugEnabled()) {
String msg = String.format(" - %-25s | %s", "loading excel ", filename);
logger.debug(msg);
}
return loadSheets(sheets);
} catch (Exception e) {
throw new TransformerDaoException("error when load excel file '" + filename + "'", e);
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
}
}
}
}
@Override
protected Map<String, Layout> loadSheets(Sheet[] sheets) throws Exception {
return parse(sheets);
}
@Override
protected Map<String, Layout> parse(Sheet[] sheets) throws Exception {
Map<String, Layout> map = new TreeMap<>();
map.putAll(parse(sheets[2]));
if(sheets.length > 3) {
map.putAll(parse(sheets[3]));
}
return map;
}
protected Map<String, Layout> parse(Sheet sheet) throws Exception {
parseColumnMapping(sheet);
Map<String, Layout> treeMap = new TreeMap<>();
try {
int columnBase = COL_BASE;
if(!sheet.getCellString(0, COL_CODE).equals(COL_REGEXP_CODE)){
columnBase = COL_CHANGE_BASE;
}
while (columnBase < 100 && sheet.existsCell(0, columnBase)) {
/**
* EAI(...) 값이 아니면 무시한다.
*/
String eaiFlag = sheet.getCellString(0, columnBase);
String layoutTypeName = sheet.getCellString(2, columnBase).trim();
if ("ASCII".equals(layoutTypeName)) {
layoutTypeName = "BYTES";
}
if ("VASCII".equals(layoutTypeName)) {
layoutTypeName = "VBYTES";
}
if (eaiFlag == null) {
break;
} else if (!eaiFlag.matches(COL_REGEXP_START_FLAG) || "".equals(layoutTypeName.trim())) {
columnBase++;
continue;
}
if (!eaiFlag.matches(COL_REGEXP_MATCH_FLAG)) {
throw new Exception("cell[0, " + columnBase + "] must be like "+ COL_REGEXP_MATCH_FLAG);
}
/**
* layout type
*/
LayoutType layoutType = layoutTypeManager.getLayoutType(layoutTypeName);
if (layoutType == null) {
throw new TransformerDaoException("LayoutTypeManager에서 LoutPtrnName을 찾을 수 없습니다. - " + layoutTypeName);
}
/**
* message
*/
StringBuffer sb = new StringBuffer();
sb.append(sheet.getCellString(1, columnBase).trim() + "_");
sb.append(sheet.getCellString(3, columnBase).trim() + "_");
sb.append(eaiFlag.substring(eaiFlag.indexOf('(')+1, eaiFlag.indexOf(')')));
String layoutName = sb.toString();
Message root = makeMessage(sheet, layoutTypeName, layoutName);
//Item rootItem = (Item) message;
root.setDepth(1);
// Default Setting
root.setDataTypeId(Types.TYPE_UNKNOWN);
root.setLength(-1);
try {
root.setDescription(sheet.getCellString(4, COL_LAYOUT_DESC).trim());
} catch(Exception e) {
root.setDescription("");
}
/**
* build item tree
*/
int rownum = 4;
root.setLayoutName(layoutName);
//rootItem.setDescription(sheet.getCellString(rownum, 3).trim());
// 2009.05.29
// 중복확인
validateLayout(layoutName, sheet, columnBase, rownum);
root = (Message) buildTree(layoutName, root, sheet, layoutTypeName, columnBase, rownum);
root.initItemParentId(0, 0);
/**
* layout
*/
Layout layout = new Layout();
layout.setName(root.getName());
layout.setDescription(root.getDescription());
layout.setBzwkDstcd(sheet.getCellString(1, columnBase).trim());
layout.setLastUpdateDate(LocalDateTime.now());
layout.setSystemInterface(sheet.getCellString(3, columnBase).trim());
layout.setRootItem(root);
root.setLayout(layout);
layout.setLayoutType(layoutType);
/**
* set overwrite -> 무조건 한다..
*/
boolean overwrite = true; //sheet.isEquals(6, 4, "O");
layout.setOverwrite(overwrite);
/**
* LayoutValidate
*/
LayoutValidator.validate(layout);
/**
* tree map 추가..
*/
treeMap.put(layout.getName(), layout);
columnBase++;
}
return treeMap;
} catch(Exception e) {
throw new TransformerDaoException(e.getMessage(), e);
}
}
private void parseColumnMapping(Sheet sheet) throws Exception {
HashMap<String, String> columnMap = new HashMap<String, String>();
columnMap.put(COL_REGEXP_LAYOUT_DESC, COL_REGEXP_LAYOUT_DESC);
columnMap.put(COL_REGEXP_NO, COL_REGEXP_NO);
columnMap.put(COL_REGEXP_DESC, COL_REGEXP_DESC);
columnMap.put(COL_REGEXP_DPTH, COL_REGEXP_DPTH);
columnMap.put(COL_REGEXP_NODE, COL_REGEXP_NODE);
columnMap.put(COL_REGEXP_OCC_TYPE, COL_REGEXP_OCC_TYPE);
columnMap.put(COL_REGEXP_OCC_REF, COL_REGEXP_OCC_REF);
// columnMap.put(COL_REGEXP_OCC_MIN, COL_REGEXP_OCC_MIN);
columnMap.put(COL_REGEXP_TYPE, COL_REGEXP_TYPE);
columnMap.put(COL_REGEXP_LEN, COL_REGEXP_LEN);
columnMap.put(COL_REGEXP_DEC_POINT_LEN, COL_REGEXP_DEC_POINT_LEN);
columnMap.put(COL_REGEXP_NAME, COL_REGEXP_NAME);
columnMap.put(COL_REGEXP_NOTE, COL_REGEXP_NOTE);
for (int i=0; i<COL_BASE+30; i++) {
if (!sheet.existsCell(0, i))
break;
String name = sheet.getCellString(0, i);
if (name == null)
continue;
if (name.replaceAll("\\s+", "").matches(COL_REGEXP_LAYOUT_DESC)) {
COL_LAYOUT_DESC = i;
columnMap.remove(COL_REGEXP_LAYOUT_DESC);
} else if (name.replaceAll("\\s+", "").matches(COL_REGEXP_NO)) {
COL_NO = i;
columnMap.remove(COL_REGEXP_NO);
} else if (name.replaceAll("\\s+", "").matches(COL_REGEXP_DESC)) {
COL_DESC = i;
columnMap.remove(COL_REGEXP_DESC);
} else if (name.replaceAll("\\s+", "").matches(COL_REGEXP_DPTH)) {
COL_DPTH = i;
columnMap.remove(COL_REGEXP_DPTH);
} else if (name.replaceAll("\\s+", "").matches(COL_REGEXP_NODE)) {
COL_NODE = i;
columnMap.remove(COL_REGEXP_NODE);
} else if (name.replaceAll("\\s+", "").matches(COL_REGEXP_OCC_TYPE)) {
COL_OCC_TYPE = i;
columnMap.remove(COL_REGEXP_OCC_TYPE);
} else if (name.replaceAll("\\s+", "").matches(COL_REGEXP_OCC_REF)) {
COL_OCC_REF = i;
columnMap.remove(COL_REGEXP_OCC_REF);
} else if (name.replaceAll("\\s+", "").matches(COL_REGEXP_TYPE)) {
COL_TYPE = i;
columnMap.remove(COL_REGEXP_TYPE);
} else if (name.replaceAll("\\s+", "").matches(COL_REGEXP_LEN)) {
COL_LEN = i;
columnMap.remove(COL_REGEXP_LEN);
} else if (name.replaceAll("\\s+", "").matches(COL_REGEXP_DEC_POINT_LEN)) {
COL_DEC_POINT_LEN = i;
columnMap.remove(COL_REGEXP_DEC_POINT_LEN);
} else if (name.replaceAll("\\s+", "").matches(COL_REGEXP_NAME)) {
COL_NAME = i;
columnMap.remove(COL_REGEXP_NAME);
} else if (name.replaceAll("\\s+", "").matches(COL_REGEXP_NOTE)) {
COL_NOTE = i;
columnMap.remove(COL_REGEXP_NOTE);
}
// else if (name.replaceAll("\\s+", "").matches(COL_REGEXP_MASK)) {
// COL_MASK = i;
// }
}
if (columnMap.size() > 0) {
StringBuilder sb = new StringBuilder();
sb.append("excel file does not have columns [");
for (Iterator iter = columnMap.keySet().iterator(); iter.hasNext(); ) {
sb.append(iter.next() + ",");
}
sb.append("] - check excel file format");
throw new Exception(sb.toString());
}
}
private Message makeMessage(Sheet sheet, String layoutTypeName, String layoutName) throws Exception {
// String nodeType = "MESSAGE";
Message message = MessageFactory.getFactory().createMessage(layoutTypeName);
((Item) message).setName(layoutName);
((Item) message).setLayoutName(layoutName);
return message;
}
private void validateLayout(String layoutName, Sheet sheet, int columnBase, int rownum) throws Exception {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int currentRow = rownum; sheet.existsRow(currentRow); currentRow++) {
String use = sheet.getCellString(currentRow, columnBase);
if (use == null || !use.trim().matches("(o|O|0|○|y|Y)")) {
continue;
}
// 일련번호 중복 처리
int seq = (new Double(sheet.getCellValue(currentRow, COL_NO))).intValue();
if(map.get(seq) != null) {
throw new Exception(layoutName + "의 일련번호가 중복되었습니다 - [row=" + currentRow + ", col=" + COL_NO + "]");
}
else {
map.put(seq, currentRow);
}
// 아이템명 중복처리
// String itemName = sheet.getCellValue(currentRow, COL_NAME);
//System.out.println("itemName===========================>"+itemName);
// if(nameMap.get(itemName) != null) {
// throw new Exception(layoutName + "의 거래(입|출)력항목명(영문)이 중복되었습니다 - [row=" + currentRow + ", col=" + COL_NAME + "]");
// }
// else {
// nameMap.put(itemName, currentRow);
// }
// 한글명 필수입력 확인
String desc = sheet.getCellValue(currentRow, COL_DESC);
if(desc == null || desc.trim().length() == 0) {
throw new Exception(layoutName + "의 거래(입|출)력항목명(한글)이 입력되지 않았습니다. - [row=" + currentRow + ", col=" + COL_DESC + "]");
}
}
map.clear();
}
private Item buildTree(String layoutName, Item parent, Sheet sheet, String layoutTypeName, int columnBase, int rownum) throws Exception {
Item item = null;
while (rownum < 1000) {
item = makeItem(sheet, layoutTypeName, columnBase, rownum);
if (item != null) {
break;
} else {
rownum++;
}
}
if (item == null) {
return parent;
}
Item next = null;
if (sheet.existsRow(rownum+1)) {
next = makeItem(sheet, layoutTypeName, columnBase, rownum+1);
}
item.setLayoutName(layoutName);
if (!sheet.existsRow(rownum)) { // 마지막일 경우
return parent;
} else if (item.getDepth() > parent.getDepth()) { // 그룹의 항목일 경우
parent.addChild(item);
item.setParent(parent);
//----------------------------------------------------
// Layout 로딩시 이중 ARRAY 등록시 에러처리 : 2009.04.08
//----------------------------------------------------
if( (item.getNodeTypeId() == Item.NODE_GROUP) && (item.getOccMax() > 1)
&& (parent.getNodeTypeId() == Item.NODE_GROUP) && (parent.getOccMax() > 1) ) {
throw new Exception("이중 ARRAY는 지원하지 않습니다. - 다음 layout item 처리시 에러 발생 - " + item.getName());
}
//----------------------------------------------------
if (next == null) {
if (sheet.existsRow(rownum+1)) {
++rownum;
// NODE_MESSAGE 또는 NODE_GROUP 일 경우에 대한 Parent ID 오류 수정 : 2009.03.11
// NODE_GROUP 다음의 필드가 'O' 가 아닐 경우
if(item.getNodeTypeId() == Item.NODE_MESSAGE || item.getNodeTypeId() == Item.NODE_GROUP) {
item = buildTree(layoutName, item, sheet, layoutTypeName, columnBase, ++rownum);
}
else {
// 2009.06.30
// Group의 하위항목의 마지막이 'O' 가 아닐 경우
// parent 계산의 문제가 있음
// 2009.10.13 그룹 다음에 'O'가 아닌 항목이 여러 개 올 경우
//---------------------------------------------------------
int p = 1;
while(true) {
next = makeItem(sheet, layoutTypeName, columnBase, rownum+p);
if(next != null || (rownum+p) >= 1000) break;
p++;
}
// next = makeItem(sheet, layoutTypeName, columnBase, rownum+1);
//---------------------------------------------------------
if(next != null) {
if(item.getDepth() > next.getDepth()) {
for (int i=0; i<item.getDepth() - next.getDepth(); i++)
parent = parent.getParent();
}
}
item = buildTree(layoutName, parent, sheet, layoutTypeName, columnBase, ++rownum);
}
}
} else if (next.getDepth() > item.getDepth()) {
item = buildTree(layoutName, item, sheet, layoutTypeName, columnBase, ++rownum);
} else if (next.getDepth() == item.getDepth()) {
parent = buildTree(layoutName, parent, sheet, layoutTypeName, columnBase, ++rownum);
} else {
for (int i=0; i<item.getDepth() - next.getDepth(); i++)
parent = parent.getParent();
parent = buildTree(layoutName, parent, sheet, layoutTypeName, columnBase, ++rownum);
}
return parent;
} else {
throw new Exception("(depth를 포함한) layout 구조를 확인하십시요 - 다음 layout item 처리시 에러 발생 - " + item.getName());
}
}
private Item makeItem(Sheet sheet, String layoutTypeName, int columnBase, int rownum) throws Exception {
if (!sheet.existsRow(rownum)
|| sheet.getCellValue(rownum, 0) == null
|| sheet.getCellValue(rownum, 1) == null) {
return null;
}
/**
* 'o|O|0|○|y|Y' 값이 아니면 null을 return 한다.
*/
String use = sheet.getCellString(rownum, columnBase);
if (use == null || !use.trim().matches("(o|O|0|○|y|Y|M|m|D)")) {
return null;
}
Item item = null;
try {
String nodeType = sheet.getCellString(rownum, COL_NODE).trim();
String name = sheet.getCellString(rownum, COL_NAME).trim();
if (name.trim().length() <= 0) {
//return null;
throw new Exception("거래입/출력항목명이 입력되지 않았습니다. [row=" + rownum + ", col=" + COL_NAME + "]");
}
else {
if(name.indexOf(".") > -1) {
throw new Exception("거래입/출력항목명에 '.'을 사용할 수 없습니다. [row=" + rownum + ", col=" + COL_NAME + "] - "+name);
}
}
int nodeTypeId = ConstantUtil.getNodeTypeId(nodeType);
item = ItemFactory.createItem(nodeTypeId);
//item.setNodeTypeId(nodeTypeId);
item.setName(name);
// 사용여부가 M/m 인 경우 Masking 필드로 설정한다.
if( "M".equalsIgnoreCase(use)) {
item.setMask("Y");
}
else {
item.setMask(" ");
}
//----------------------------------------------------------------
// 2009.05.29
// 일련번호는 0보다 큰 값이어야 한다.
try {
item.setSeqNo((new Double(sheet.getCellValue(rownum, COL_NO))).intValue());
} catch (NumberFormatException e) {
throw new Exception("sequence number is invalid value [row=" + rownum + ", col=" + COL_NO + "]='" + sheet.getCellValue(rownum, COL_NO) +
"' - " + e.getMessage());
// logger.warn("sequence number is invalid value [row=" + rownum + ", col=" + COL_NO + "]='" + sheet.getCellValue(rownum, COL_NO) +
// "' - " + e.getMessage());
// item.setSeqNo(-1);
}
if(item.getSeqNo() < 1) {
throw new Exception(item.getName() + " - 일련번호는 0보다 커야 합니다.");
}
//----------------------------------------------------------------
if (sheet.getCellInt(rownum, COL_DPTH) <= 0) {
throw new Exception(item.getName() + "'s DEPTH = '" + sheet.getCellInt(rownum, COL_DPTH) +
"', 'DEPTH' value must be greate than 0");
}
item.setDepth(sheet.getCellInt(rownum, COL_DPTH) + 1);
item.setDescription(sheet.getCellString(rownum, COL_DESC).trim());
item.setDataTypeRef(sheet.getCellString(rownum, COL_TYPE).trim());
// 2010.01.18 권세환대리
// 필드설명에 '비밀'이라는 문자가 있으면 강제 Masking
if(item.getDescription() != null && item.getDescription().indexOf("비밀") != -1) {
item.setMask("Y");
}
// 2009.03.20
// nodeTypeId 이 NODE_MESSAGE, NODE_GROUP 면 DataTypeId 를 강제로 TYPE_UNKNOWN 설정
// XLS 등록시 오류방지
if(nodeTypeId == Item.NODE_MESSAGE || nodeTypeId == Item.NODE_GROUP) {
item.setDataTypeId(Types.TYPE_UNKNOWN);
}
else {
item.setDataTypeId(ConstantUtil.getDataTypeId(sheet.getCellString(rownum, COL_TYPE).trim(), layoutTypeName));
}
try {
/*
// PIC S9(n)V9(d) 인 경우 길이에 (+1) 하도록 한다.
if( "PIC S9(n)V9(d)".equals(item.getDataTypeRef()) ) {
item.setLength(sheet.getCellInt(rownum, COL_LEN)+1);
}
else {
item.setLength(sheet.getCellInt(rownum, COL_LEN));
}
*/
item.setLength(sheet.getCellInt(rownum, COL_LEN));
} catch (Exception e) {
item.setLength(0);
}
try {
item.setDecimalPointLength(sheet.getCellInt(rownum, COL_DEC_POINT_LEN));
} catch (Exception e) {
item.setDecimalPointLength(0);
}
/**
* occRef
*/
item.setOccRef(sheet.getCellString(rownum, COL_OCC_REF).trim());
if (!"".equals(item.getOccRef())) {
item.setOccType("+");
}
/**
* occType
*/
String occType = sheet.getCellString(rownum, COL_OCC_TYPE).trim();
item.setOccType(occType);
Matcher m = Pattern.compile("([0-9]+)\\.\\.([0-9]*)").matcher(occType);
if (m.find()) {
item.setOccMin(Integer.parseInt(m.group(1)));
if ("".equals(m.group(2))) {
item.setOccMax(Integer.MAX_VALUE);
} else {
item.setOccMax(Integer.parseInt(m.group(2)));
}
} else if (("?".equals(occType.trim()))) {
item.setOccMin(0);
item.setOccMax(1);
} else if (("*".equals(occType.trim()))) {
item.setOccMin(0);
item.setOccMax(-1);
} else if (("+".equals(occType.trim()))) {
item.setOccMin(1);
item.setOccMax(-1);
} else if (("".equals(occType.trim()))) {
item.setOccMin(1);
item.setOccMax(1);
} else if (occType.trim().matches("[0-9]+")) {
item.setOccMax(Integer.parseInt(occType.trim()));
//--------------------------------------------------------
// 2009.09.14 강길수 차장 요청
// 반복참조회수가 있는 경우 최소값을 0인 가변배열로 정의하도록 수정
if (item.getOccRef() != null && !"".equals(item.getOccRef().trim())) {
item.setOccMin(0);
}
else {
item.setOccMin(Integer.parseInt(occType.trim()));
}
//--------------------------------------------------------
} else {
throw new Exception("OccType 값이 잘못 설정되었습니다. - " + occType);
}
/**
* path
*/
if (layoutTypeName.startsWith("FML"))
item.setPath(sheet.getCellString(rownum, COL_NOTE).trim());
if (use.trim().equals("D")){
item.setDefaultValue(sheet.getCellString(rownum, COL_DEFAULT).trim());
}
return item;
} catch(Exception e) {
String itemName = "";
if(item != null) {
itemName = item.getName();
}
throw new Exception("error when read item : " + itemName, e);
}
}
@Override
protected Map<String, Layout> removeSheets(Sheet[] sheets) throws Exception {
return Collections.emptyMap();
}
public Layout findLayoutByName(String layoutName) {
return null;
}
public Item findItemByName(String layoutName) {
return null;
}
public Map<String, Layout> findPermanent(){
return Collections.emptyMap();
}
public String getSheetName() {
return SHEET_NAME;
}
}
@@ -0,0 +1,32 @@
package com.eactive.eai.transformer.dao.excel;
import java.util.Map;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.transformer.dao.jdbc.LayoutTypeJdbcDao;
import com.eactive.eai.transformer.layout.Layout;
import com.eactive.eai.transformer.layout.LayoutTypeManager;
public class Layout2ExcelLoadDao extends Layout2ExcelDao {
//LayoutTypeManager layoutTypeManager = LayoutTypeManager.getInstance();
public Layout2ExcelLoadDao() {
super();
layoutTypeManager = LayoutTypeManager.getInstance();
layoutTypeManager.reload();
// if (!layoutTypeManager.isStarted()) {
// LayoutTypeJdbcDao layoutTypeJdbcDao = ApplicationContextProvider.getContext()
// .getBean(LayoutTypeJdbcDao.class);
// layoutTypeManager.init(layoutTypeJdbcDao.load());
// }
}
public Map<String, Layout> load(Sheet[] sheets) throws Exception {
return parse(sheets);
}
public Map<String, Layout> load(Sheet sheet) throws Exception {
return parse(sheet);
}
}
@@ -0,0 +1,314 @@
package com.eactive.eai.transformer.dao.excel;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.eactive.eai.data.entity.onl.transformer.layout.LayoutEntity;
import com.eactive.eai.transformer.dao.TransformerDaoException;
import com.eactive.eai.transformer.layout.Item;
import com.eactive.eai.transformer.layout.ItemFactory;
import com.eactive.eai.transformer.layout.Layout;
import com.eactive.eai.transformer.layout.LayoutManager;
import com.eactive.eai.transformer.layout.LayoutType;
import com.eactive.eai.transformer.layout.LayoutTypeManager;
import com.eactive.eai.transformer.layout.LayoutValidator;
import com.eactive.eai.transformer.layout.loader.LayoutLoader;
import com.eactive.eai.transformer.layout.mapper.LayoutMapper;
import com.eactive.eai.transformer.message.Message;
import com.eactive.eai.transformer.message.MessageException;
import com.eactive.eai.transformer.message.MessageFactory;
import com.eactive.eai.transformer.util.ConstantUtil;
@Service
public class LayoutExcelDao extends BaseExcelDao<String, Layout> {
private static final int DATA_ROW_OFFSET = 10;
private static final int COL_NO = 0;
private static final int COL_NODE = 1;
private static final int COL_DPTH = 2;
private static final int COL_NAME = 3;
private static final int COL_DESC = 4;
private static final int COL_TYPE = 5;
private static final int COL_LEN = 6;
private static final int COL_PATH = 7;
private static final int COL_OCC_TYPE = 8;
private static final int COL_OCC_MIN = 9;
private static final int COL_DEF_VAL = 10;
private static final int COL_REF = 11;
private static final int COL_OCC_REF = 12;
private static final int COL_MASK = 13;
private static final int COL_LAYOUT_TYPE_COL = 2;
private static final int COL_LAYOUT_TYPE_ROW = 8;
private static final int COL_DPLEN = 14;
@Autowired
private LayoutTypeManager layoutTypeManager;
@Autowired
private LayoutLoader layoutLoader;
@Autowired
private LayoutMapper layoutMapper;
public LayoutExcelDao() {
super("layout");
}
public Layout findLayoutByName(String layoutName) {
return null;
}
public Item findItemByName(String layoutName) {
Layout l = LayoutManager.getManager().getLayoutByName(layoutName);
if (l != null) {
return l.getRootItem();
} else {
return null;
}
}
protected Map<String, Layout> loadSheets(Sheet[] sheets) {
Map<String, Layout> map = parse(sheets);
return map;
}
protected Map<String, Layout> removeSheets(Sheet[] sheets) throws Exception {
Item rootItem = (Item) parse(sheets);
try {
layoutLoader.deleteById(rootItem.getName());
} catch (Exception e) {
throw e;
}
return null;
}
protected Map<String, Layout> parse(Sheet[] sheets) {
try {
Sheet sheet = sheets[0];
/**
* layout type
*/
String layoutTypeName = sheet.getCellString(COL_LAYOUT_TYPE_ROW, COL_LAYOUT_TYPE_COL).trim();
LayoutType layoutType = layoutTypeManager.getLayoutType(layoutTypeName);
if (layoutType == null) {
throw new TransformerDaoException("LayoutTypeManager에서 LoutPtrnName을 찾을 수 없습니다. - " + layoutTypeName);
}
/**
* build item tree
*/
int rownum = DATA_ROW_OFFSET;
Item top = makeItem(sheet, layoutTypeName, rownum++);
String layoutName = top.getName();
top.setLayoutName(layoutName);
top = buildTree(layoutName, top, sheet, layoutTypeName, rownum);
top.initItemParentId(0, 0);
/**
* layout
*/
Layout layout = new Layout();
layout.setName(top.getName());
layout.setDescription(top.getDescription());
// layout.setBzwkDstcd(???);
layout.setLastUpdateDate(LocalDateTime.now());
layout.setRootItem(top);
((Message) top).setLayout(layout);
layout.setLayoutType(layoutType);
/**
* set overwrite
*/
boolean overwrite = sheet.isEquals(6, 4, "O");
layout.setOverwrite(overwrite);
/**
* map
*/
Map<String, Layout> treeMap = new TreeMap<>();
treeMap.put(layout.getName(), layout);
return treeMap;
} catch (Exception e) {
throw new TransformerDaoException(e.getMessage(), e);
}
}
private Item buildTree(String layoutName, Item parent, Sheet sheet, String messageType, int rownum)
throws Exception {
Item item = makeItem(sheet, messageType, rownum);
Item next = makeItem(sheet, messageType, rownum + 1);
item.setLayoutName(layoutName);
if (!sheet.existsRow(rownum)) {
return parent;
} else if (item.getDepth() > parent.getDepth()) {
try {
parent.addChild(item);
} catch (UnsupportedOperationException e) {
StringBuffer sb = new StringBuffer();
sb.append(layoutName);
sb.append(" | cannot add item to parent - ");
sb.append("parent=(" + parent.getNodeType() + ", " + parent.getName() + ", " + parent.getDepth() + ")");
sb.append(", item=(" + item.getNodeType() + ", " + item.getName() + ", " + item.getDepth() + ")");
throw new Exception(sb.toString(), e);
}
item.setParent(parent);
if (next == null) {
} else if (next.getDepth() > item.getDepth()) {
item = buildTree(layoutName, item, sheet, messageType, ++rownum);
} else if (next.getDepth() == item.getDepth()) {
parent = buildTree(layoutName, parent, sheet, messageType, ++rownum);
} else {
for (int i = 0; i < item.getDepth() - next.getDepth(); i++)
parent = parent.getParent();
parent = buildTree(layoutName, parent, sheet, messageType, ++rownum);
}
return parent;
} else {
throw new Exception("invalid depth : " + item);
}
}
private Item makeItem(Sheet sheet, String messageType, int rownum) throws Exception {
if (sheet.getCellValue(rownum, 0) == null || sheet.getCellValue(rownum, 1) == null)
return null;
Item item = null;
try {
String nodeType = sheet.getCellString(rownum, COL_NODE).trim();
String name = sheet.getCellString(rownum, COL_NAME).trim();
String layoutTypeName = sheet.getCellString(COL_LAYOUT_TYPE_ROW, COL_LAYOUT_TYPE_COL).trim();
if (name.trim().length() <= 0)
return null;
if ("MESSAGE".equals(nodeType) || "INCLUDE".equals(nodeType)) {
item = MessageFactory.getFactory().createMessage(layoutTypeName);
} else {
int nodeTypeId = ConstantUtil.getNodeTypeId(sheet.getCellString(rownum, COL_NODE).trim());
item = ItemFactory.createItem(nodeTypeId);
}
item.setName(sheet.getCellString(rownum, COL_NAME).trim());
if ("MESSAGE".equals(nodeType) || "INCLUDE".equals(nodeType)) {
item.setLayoutName(item.getName());
}
try {
item.setSeqNo((new Double(sheet.getCellValue(rownum, COL_NO))).intValue());
} catch (NumberFormatException e) {
logger.warn("sequence number is invalid value[row=" + rownum + ", col=" + COL_NO + "]='"
+ sheet.getCellValue(rownum, COL_NO) + "' - " + e.getMessage());
item.setSeqNo(-1);
}
item.setDepth(sheet.getCellInt(rownum, COL_DPTH));
item.setDescription(sheet.getCellString(rownum, COL_DESC).trim());
item.setDataTypeRef(sheet.getCellString(rownum, COL_TYPE).trim());
item.setDataTypeId(ConstantUtil.getDataTypeId(sheet.getCellString(rownum, COL_TYPE).trim(), messageType));
item.setPath(sheet.getCellString(rownum, COL_PATH).trim());
try {
item.setLength(sheet.getCellInt(rownum, COL_LEN));
} catch (Exception e) {
throw new RuntimeException("Length 값이 잘못 설정되었습니다. - " + sheet.getCellString(rownum, COL_LEN).trim(), e);
}
try {
item.setDecimalPointLength(sheet.getCellInt(rownum, COL_DPLEN));
} catch (Exception e) {
item.setDecimalPointLength(0);
}
item.setRefInfo(sheet.getCellString(rownum, COL_REF).trim());
/**
* log masking
*/
if (sheet.getCellString(rownum, COL_MASK).trim().matches("(o|O|0|○|y|Y)")) {
item.setMask("Y");
}
item.setOccRef(sheet.getCellString(rownum, COL_OCC_REF).trim());
String occType = sheet.getCellString(rownum, COL_OCC_TYPE).trim();
item.setOccType(occType);
Matcher m = Pattern.compile("([0-9]+)\\.\\.([0-9]*)").matcher(occType);
if (m.find()) {
item.setOccMin(Integer.parseInt(m.group(1)));
if ("".equals(m.group(2))) {
item.setOccMax(Integer.MAX_VALUE);
} else {
item.setOccMax(Integer.parseInt(m.group(2)));
}
} else if (("?".equals(occType.trim()))) {
item.setOccMin(sheet.getCellInt(rownum, COL_OCC_MIN));
item.setOccMax(1);
} else if (("*".equals(occType.trim()))) {
item.setOccMin(sheet.getCellInt(rownum, COL_OCC_MIN));
item.setOccMax(-1);
} else if (("+".equals(occType.trim()))) {
item.setOccMin(sheet.getCellInt(rownum, COL_OCC_MIN));
item.setOccMax(-1);
} else if (occType.trim().matches("[0-9]+")) {
item.setOccMin(sheet.getCellInt(rownum, COL_OCC_MIN));
item.setOccMax(Integer.parseInt(occType.trim()));
} else {
throw new MessageException("발생유형 값이 잘못 설정되었습니다. - '" + occType + "'");
}
item.setDefaultValue(sheet.getCellString(rownum, COL_DEF_VAL).trim());
return item;
} catch (Exception e) {
throw new Exception("error when read item : " + (item == null ? "" : item.getName()), e);
}
}
public void save(Map<String, Layout> layoutMap) {
layoutMap.values().stream().forEach(this::saveLayout);
}
public void saveLayout(final Layout layout) {
if (layout.getName() == null) {
throw new TransformerDaoException("layout name cannot be null");
} else if (layout.getDescription() == null) {
throw new TransformerDaoException("layout descriptions cannot be null");
} else if (layout.getLayoutType().getName() == null) {
throw new TransformerDaoException("layout type name cannot be null");
}
if (logger.isInfoEnabled()) {
logger.info(String.format(" + %-25s | %s (%s)", "save layout", (layout == null ? "" : layout.getName()),
(layout == null ? "" : layout.getLayoutType().getName())));
}
LayoutValidator.validate(layout);
/**
* overwrite?
*/
if (layout.getOverwrite()) {
layoutLoader.findById(layout.getName()).ifPresent(layoutLoader::delete);
}
LayoutEntity layoutEntity = layoutMapper.toEntity(layout);
layoutEntity.setUseyn("1");
layoutLoader.save(layoutEntity);
}
}
@@ -0,0 +1,135 @@
package com.eactive.eai.transformer.dao.excel;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import com.eactive.eai.common.util.Logger;
public class LayoutExcelLoadFormatManager {
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
private static LayoutExcelLoadFormatManager instance;
public static String LAYOUT_EXCEL_LOAD_FORMAT_CONFIG = "excel.layout.load.format.config";
private String DEFAULT_CONFIG_PATH = "./resources/excel-layout-load-format.properties";
private String DEFAULT_CONFIG_FILE = "excel-layout-load-format.properties";
private Map<String, String> map = new HashMap<>();;
private LayoutExcelLoadFormatManager() {
map = new HashMap<>();
}
public static LayoutExcelLoadFormatManager getInstance() {
if (instance == null) {
instance = new LayoutExcelLoadFormatManager();
instance.init();
}
return instance;
}
public String getData(String name) {
return map.get(name);
}
public int getInt(String name) {
String s = map.get(name);
int r = 0;
try {
r = Integer.parseInt(s);
} catch (Exception e) {
}
return r;
}
@SuppressWarnings("rawtypes")
public void init() {
try {
Properties config = loadConfigFile();
logger.debug(config.toString());
map = propertyToMap(config);
} catch (Exception ex) {
ex.printStackTrace();
logger.error("init failed", ex);
}
}
private HashMap<String, String> propertyToMap(Properties prop) {
HashMap<String, String> retMap = new HashMap<>();
for (Map.Entry<Object, Object> entry : prop.entrySet()) {
retMap.put(String.valueOf(entry.getKey()).trim(), String.valueOf(entry.getValue()).trim());
}
return retMap;
}
private Properties loadConfigFile() throws Exception {
String configFile = getConfigFile();
return loadConfigFileProperties(configFile);
}
private Properties loadConfigFileProperties(String configFile) throws Exception {
try {
return loadFileProperties(configFile);
} catch (Exception e) {
logger.warn("LayoutExcelLoadFormatManager | loadFileProperties failed. - " + configFile + ", "
+ e.getMessage());
}
// try classpath file
return loadClassPathProperties(configFile);
}
private Properties loadFileProperties(String filePath) throws Exception {
logger.debug("configFile : ", filePath);
Properties p = new Properties();
try (InputStream in = new FileInputStream(filePath)) {
p.load(in);
return p;
} catch (Exception e) {
throw new Exception("LayoutExcelLoadFormatManager | Cannot load config file. - " + filePath, e);
}
}
private Properties loadClassPathProperties(String filePath) throws Exception {
Properties p = new Properties();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
logger.warn("LayoutExcelLoadFormatManager | ClassLoader : load. - " + filePath);
try (InputStream in = classLoader.getResourceAsStream(filePath)) {
p.load(in);
return p;
} catch (Exception e) {
if (logger.isWarn()) {
logger.warn("LayoutExcelLoadFormatManager | ClassLoader : Cannot load config file. - " + filePath + ", "
+ e.getMessage());
}
}
logger.warn("LayoutExcelLoadFormatManager | ClassLoader : load default - " + DEFAULT_CONFIG_FILE);
try (InputStream in = classLoader.getResourceAsStream(DEFAULT_CONFIG_FILE)) {
p.load(in);
logger.warn("LayoutExcelLoadFormatManager | ClassLoader : load default success - " + DEFAULT_CONFIG_FILE);
return p;
} catch (Exception e) {
logger.error("LayoutExcelLoadFormatManager | ClassLoader : Cannot load default config file. - "
+ DEFAULT_CONFIG_FILE, e);
throw new Exception("LayoutExcelLoadFormatManager | ClassLoader : Cannot load default config file. - "
+ DEFAULT_CONFIG_FILE, e);
}
}
private String getConfigFile() {
String configFilePath = System.getProperty(LAYOUT_EXCEL_LOAD_FORMAT_CONFIG);
if (StringUtils.isEmpty(configFilePath)) {
return DEFAULT_CONFIG_PATH;
} else {
return configFilePath;
}
}
public static void main(String[] args) throws Exception {
LayoutExcelLoadFormatManager.getInstance();
}
}
@@ -0,0 +1,123 @@
package com.eactive.eai.transformer.dao.excel;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.eactive.eai.data.entity.onl.transformer.layout.LayoutTypeEntity;
import com.eactive.eai.transformer.dao.TransformerDaoException;
import com.eactive.eai.transformer.layout.LayoutType;
import com.eactive.eai.transformer.layout.loader.LayoutTypeLoader;
import com.eactive.eai.transformer.layout.mapper.LayoutTypeMapper;
@Service
@Transactional
public class LayoutTypeExcelDao extends BaseExcelDao<String, LayoutType> {
private static final int DATA_ROW_OFFSET = 10;
private static final int COL_NAME = 1;
private static final int COL_DESC = 2;
private static final int COL_CLAS = 3;
@Autowired
private LayoutTypeLoader layoutTypeLoader;
@Autowired
private LayoutTypeMapper layoutTypeMapper;
public LayoutTypeExcelDao() throws TransformerDaoException {
super("layout_type");
}
protected Map<String, LayoutType> parse(Sheet[] sheets) throws TransformerDaoException {
Map<String, LayoutType> map = new TreeMap<>();
Sheet sheet = sheets[0];
LayoutType layoutType = null;
try {
for (int currentRow = DATA_ROW_OFFSET; sheet.existsRow(currentRow); currentRow++) {
try {
String name = sheet.getCellString(currentRow, COL_NAME);
if (name.trim().length() > 0) {
layoutType = new LayoutType();
layoutType.setName(name);
layoutType.setDescription(sheet.getCellString(currentRow, COL_DESC));
layoutType.setGenClass(sheet.getCellString(currentRow, COL_CLAS));
/**
* set overwrite
*/
boolean overwrite = sheet.isEquals(6, 4, "O");
layoutType.setOverwrite(overwrite);
map.put(layoutType.getName(), layoutType);
} else {
break;
}
} catch (Exception e) {
logger.error("[ERROR] !!!!! " + e.getMessage() + " - ROW: " + currentRow, e);
}
}
} catch (Exception e) {
throw new TransformerDaoException(e.getMessage(), e);
}
return map;
}
/**
* LayoutTypeDao Interface
*/
public LayoutType findLayoutTypeByName(String typeName) throws TransformerDaoException {
return null;
}
/**
* ExcelJob Interface
*/
protected Map<String, LayoutType> loadSheets(Sheet[] sheets) throws TransformerDaoException {
Map<String, LayoutType> map = parse(sheets);
return map;
}
@SuppressWarnings("rawtypes")
public void save(Map layouttypeMap) {
if (logger.isInfoEnabled()) {
logger.info(" + save layout types");
}
for (Iterator iter = layouttypeMap.values().iterator(); iter.hasNext();) {
LayoutType layoutType = (LayoutType) iter.next();
if (layoutType == null) {
continue;
}
if (layoutType.getOverwrite()) {
layoutTypeLoader.findById(layoutType.getName()).ifPresent(layoutTypeLoader::delete);
}
LayoutTypeEntity layoutTypeEntity = layoutTypeMapper.toEntity(layoutType);
layoutTypeLoader.save(layoutTypeEntity);
}
}
@Override
protected Map<String, LayoutType> removeSheets(Sheet[] sheets) throws TransformerDaoException {
try {
layoutTypeLoader.deleteAll(layoutTypeLoader.findAll());
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}
}
@@ -0,0 +1,12 @@
package com.eactive.eai.transformer.dao.excel;
public interface Sheet {
public String getCellString(int row, int column) throws Exception;
public int getCellInt(int row, int column) throws Exception;
public boolean existsRow(int row) throws Exception;
public boolean existsCell(int row, int col) throws Exception;
public boolean isEquals(int row, int column, String value) throws Exception;
public String getCellValue(int row, int column);
public String toString();
}
@@ -0,0 +1,172 @@
package com.eactive.eai.transformer.dao.excel;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.eactive.eai.data.entity.onl.transformer.transform.TransformEntity;
import com.eactive.eai.transformer.dao.TransformerDaoException;
import com.eactive.eai.transformer.dao.jdbc.LayoutJdbcDao;
import com.eactive.eai.transformer.layout.Layout;
import com.eactive.eai.transformer.layout.LayoutManager;
import com.eactive.eai.transformer.transform.Transform;
import com.eactive.eai.transformer.transform.TransformItem;
import com.eactive.eai.transformer.transform.TransformValidator;
import com.eactive.eai.transformer.transform.loader.TransformLoader;
import com.eactive.eai.transformer.transform.mapper.TransformEntityMapper;
@Service
@Transactional
public class TransformExcelDao extends BaseExcelDao<String, Transform> {
private static final int DATA_ROW_OFFSET = 13;
private static final int COL_TRAN_INFO = 2;
private static final int ROW_TRAN_NAME = 8;
private static final int ROW_TRAN_DESC = 9;
private static final int ROW_TRAN_TRG_LOUT = 10;
private static final int ROW_TRAN_SRC_LOUT = 11;
private static final int COL_INST = 2;
private static final int COL_RES_PATH = 3;
private static final int COL_SEQ = 4;
private static final int COL_DEF_VALU = 5;
@Autowired
private LayoutManager layoutManager;
@Autowired
private TransformLoader transformLoader;
@Autowired
private TransformEntityMapper transformEntityMapper;
@Autowired
private LayoutJdbcDao layoutJdbcDao;
public TransformExcelDao() {
super("transform");
}
protected Map<String, Transform> parse(Sheet[] sheets) {
Transform transform = new Transform();
Sheet sheet = sheets[0];
// 변환 기본 정보
try {
transform.setName(sheet.getCellString(ROW_TRAN_NAME, COL_TRAN_INFO));
transform.setDescription(sheet.getCellString(ROW_TRAN_DESC, COL_TRAN_INFO));
transform.setLastUpdateDate(getCurrentDateTime().substring(0, 16));
String targetLayoutName = sheet.getCellString(ROW_TRAN_TRG_LOUT, COL_TRAN_INFO);
Layout targetLayout = layoutManager.getLayoutByName(targetLayoutName);
if (targetLayout == null) {
targetLayout = layoutJdbcDao.load(targetLayoutName);
if (targetLayout == null)
throw new Exception("해당 TARGET LAYOUT을 찾을 수 없습니다. - " + targetLayoutName);
layoutManager.putLayout(targetLayout);
}
transform.setTargetLayout(targetLayout);
String sourceLayoutNames = sheet.getCellString(ROW_TRAN_SRC_LOUT, COL_TRAN_INFO);
StringTokenizer tokens = new StringTokenizer(sourceLayoutNames, "\n");
while (tokens.hasMoreTokens()) {
String sourceLayoutName = tokens.nextToken().trim();
Layout sourceLayout = layoutManager.getLayoutByName(sourceLayoutName);
if (sourceLayout == null) {
sourceLayout = layoutJdbcDao.load(sourceLayoutName);
if (sourceLayout == null)
throw new Exception("해당 SOURCE LAYOUT을 찾을 수 없습니다. - " + sourceLayoutName);
layoutManager.putLayout(sourceLayout);
}
transform.addSourceLayout(sourceLayout);
}
for (int currentRow = DATA_ROW_OFFSET; sheet.existsRow(currentRow); currentRow++) {
TransformItem item = new TransformItem();
item.setTransform(transform);
item.setResultItemPath(sheet.getCellString(currentRow, COL_RES_PATH));
item.setInstruction(sheet.getCellString(currentRow, COL_INST));
item.setDefaultValue(sheet.getCellString(currentRow, COL_DEF_VALU));
if ("".equals(item.getResultItemPath().trim()))
break;
try {
item.setSeqNo(sheet.getCellInt(currentRow, COL_SEQ));
} catch (Exception e) {
item.setSeqNo(999);
}
transform.addTransformItem(item);
}
/**
* set overwrite
*/
boolean overwrite = sheet.isEquals(6, 4, "O");
transform.setOverwrite(overwrite);
Map<String, Transform> map = new TreeMap<>();
map.put(transform.getName(), transform);
return map;
} catch (Exception e) {
throw new TransformerDaoException(e.getMessage(), e);
}
}
public Transform findTransformByName(String transformName) {
return null;
}
/**
* ExcelJob Interface
*/
protected Map<String, Transform> loadSheets(Sheet[] sheets) {
return parse(sheets);
}
protected Map<String, Transform> removeSheets(Sheet[] sheets) throws Exception {
String transformName = sheets[0].getCellString(ROW_TRAN_NAME, COL_TRAN_INFO);
transformLoader.deleteById(transformName);
return null;
}
public void save(Map<String, Transform> transformMap) throws Exception {
for (Iterator<Transform> iter = transformMap.values().iterator(); iter.hasNext();) {
Transform transform = iter.next();
TransformValidator.validate(transform, true);
saveTransform(transform);
}
}
public void saveTransform(final Transform transform) {
if (transform == null) {
return;
}
if (logger.isInfoEnabled()) {
logger.info(" + save transform | %s" + transform.getName());
}
/**
* overwrite?
*/
if (transform.getOverwrite()) {
transformLoader.findById(transform.getName()).ifPresent(transformLoader::delete);
}
TransformEntity transformEntity = transformEntityMapper.toEntity(transform);
transformLoader.save(transformEntity);
}
}
@@ -0,0 +1,62 @@
package com.eactive.eai.transformer.dao.jdbc;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.data.entity.onl.transformer.function.Function;
import com.eactive.eai.transformer.dao.FunctionDao;
import com.eactive.eai.transformer.function.FunctionDefinition;
import com.eactive.eai.transformer.function.loader.FunctionLoader;
import com.eactive.eai.transformer.function.mapper.FunctionMapper;
@Service
@Transactional
public class FunctionJdbcDao extends TransDao implements FunctionDao {
private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
@Autowired
private FunctionLoader functionLoader;
@Autowired
private FunctionMapper functionMapper;
public Map<String, FunctionDefinition> load() {
if (logger.isInfoEnabled()) {
logger.info("FunctionJdbcDao | loading... ");
}
Map<String, FunctionDefinition> map = new TreeMap<>();
try (Stream<Function> functions = functionLoader.loadAll()) {
functions.forEach(f -> {
FunctionDefinition fd = functionMapper.toVo(f);
map.put(fd.getName(), fd);
});
}
if (logger.isDebugEnabled()) {
logger.debug("FunctionJdbcDao | 함수 정보를 가져왔음 - " + map.size());
}
return map;
}
public FunctionDefinition findFunctionByName(String cnvsnFuntnname) {
Optional<Function> functionOptional = functionLoader.findById(cnvsnFuntnname);
if (!functionOptional.isPresent()) {
return null;
}
Function function = functionOptional.get();
return functionMapper.toVo(function);
}
}
@@ -0,0 +1,98 @@
package com.eactive.eai.transformer.dao.jdbc;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.eactive.eai.common.property.loader.PropGroupLoader;
import com.eactive.eai.data.entity.onl.property.PropGroup;
import com.eactive.eai.data.entity.onl.transformer.layout.LayoutEntity;
import com.eactive.eai.transformer.dao.LayoutDao;
import com.eactive.eai.transformer.dao.TransformerDaoException;
import com.eactive.eai.transformer.layout.Item;
import com.eactive.eai.transformer.layout.Layout;
import com.eactive.eai.transformer.layout.loader.LayoutLoader;
import com.eactive.eai.transformer.layout.mapper.LayoutMapper;
import com.eactive.eai.transformer.util.MemoryLogger;
@Service
@Transactional
public class LayoutJdbcDao extends TransDao implements LayoutDao {
@Autowired
private PropGroupLoader propGroupLoader;
@Autowired
private LayoutLoader layoutLoader;
@Autowired
private LayoutMapper layoutMapper;
@Override
public Map<String, Layout> load() {
Stream<LayoutEntity> layoutEntities = layoutLoader.loadAll();
Map<String, Layout> resultMap = new ConcurrentHashMap<>();
layoutEntities.forEach(layoutEntity -> {
Layout layout = load(layoutEntity);
if (layout != null) {
resultMap.put(layout.getName(), layout);
}
});
return resultMap;
}
public Layout load(LayoutEntity layoutEntity) {
Layout layout = null;
try {
layout = layoutMapper.toVo(layoutEntity);
} catch (Exception e) {
MemoryLogger.error(e.getMessage(), e);
logger.error(e.getMessage(), e);
}
return layout;
}
public Layout load(String layoutName) {
LayoutEntity layoutEntity = layoutLoader.getById(layoutName);
if (!"1".equals(layoutEntity.getUseyn())) {
return null;
}
try {
return load(layoutEntity);
} catch (Exception e) {
MemoryLogger.error(e.getMessage(), e);
logger.error(e.getMessage(), e);
throw new TransformerDaoException(e.getMessage(), e);
}
}
@Override
public Layout findLayoutByName(String loutName) {
LayoutEntity layoutEntity = layoutLoader.getById(loutName);
return load(layoutEntity);
}
@Override
public Item findItemByName(String layoutName) {
return load(layoutName).getRootItem();
}
@Override
public Map<String, String> findPermanent() {
Map<String, String> map = new HashMap<>();
PropGroup propGroup = propGroupLoader.getById("PERMANENT_LAYOUT");
propGroup.getProps().forEach(prop -> map.put(prop.getPrpty2val(), prop.getPrpty2val()));
return map;
}
}
@@ -0,0 +1,55 @@
package com.eactive.eai.transformer.dao.jdbc;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.eactive.eai.data.entity.onl.transformer.layout.LayoutTypeEntity;
import com.eactive.eai.transformer.dao.LayoutTypeDao;
import com.eactive.eai.transformer.layout.LayoutType;
import com.eactive.eai.transformer.layout.loader.LayoutTypeLoader;
import com.eactive.eai.transformer.layout.mapper.LayoutTypeMapper;
@Service
@Transactional
public class LayoutTypeJdbcDao extends TransDao implements LayoutTypeDao {
@Autowired
private LayoutTypeLoader layoutTypeLoader;
@Autowired
private LayoutTypeMapper layoutTypeMapper;
public Map<String, LayoutType> load() {
if (logger.isInfoEnabled()) {
logger.info("LayoutTypeJdbcDao | loading... ");
}
Map<String, LayoutType> map = new TreeMap<>();
List<LayoutTypeEntity> layoutTypeEntities = layoutTypeLoader.findAll();
for (LayoutTypeEntity layoutTypeEntity : layoutTypeEntities) {
LayoutType layoutType = layoutTypeMapper.toVo(layoutTypeEntity);
map.put(layoutType.getName(), layoutType);
}
if (logger.isDebugEnabled()) {
logger.debug("LayoutTypeJdbcDao | LayouType 정보를 Load 했습니다. - " + map.size());
}
return map;
}
public void clearAllLayoutTypes() {
layoutTypeLoader.deleteAll(layoutTypeLoader.findAll());
}
public LayoutType findLayoutTypeByName(String loutPtrnName) {
return layoutTypeLoader.findById(loutPtrnName).map(layoutTypeMapper::toVo).orElse(null);
}
}
@@ -0,0 +1,21 @@
package com.eactive.eai.transformer.dao.jdbc;
import java.math.BigDecimal;
import com.eactive.eai.transformer.util.Logger;
public class TransDao {
protected static Logger logger = Logger.getLogger("transformer");
protected int convertInt(Object o) {
if (o instanceof Integer) {
return (Integer) o;
} else if (o instanceof BigDecimal) {
return ((BigDecimal) o).intValue();
} else {
return 0;
}
}
}
@@ -0,0 +1,71 @@
package com.eactive.eai.transformer.dao.jdbc;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.eactive.eai.data.entity.onl.transformer.transform.TransformEntity;
import com.eactive.eai.transformer.dao.TransformDao;
import com.eactive.eai.transformer.layout.LayoutManager;
import com.eactive.eai.transformer.transform.Transform;
import com.eactive.eai.transformer.transform.loader.TransformLoader;
import com.eactive.eai.transformer.transform.mapper.TransformEntityMapper;
import com.eactive.eai.transformer.util.MemoryLogger;
@Service
@Transactional
public class TransformJdbcDao extends TransDao implements TransformDao {
@Autowired
private TransformLoader transformLoader;
@Autowired
private TransformEntityMapper transformEntityMapper;
@Autowired
private LayoutManager layoutManager;
public Map<String, Transform> load() {
if (logger.isInfoEnabled()) {
logger.info("TransformJdbcDao | loading... ");
}
Stream<TransformEntity> transformEntities = transformLoader.loadAll();
if (logger.isInfoEnabled()) {
logger.info("TransformJdbcDao | make transform... ");
}
return load(transformEntities);
}
private Map<String, Transform> load(Stream<TransformEntity> transformEntities) {
Map<String, Transform> map = new TreeMap<>();
transformEntities.map(this::load).filter(e -> e != null).forEach(t -> map.put(t.getName(), t));
return map;
}
public Transform load(TransformEntity transformEntity) {
Transform transform = null;
try {
transform = transformEntityMapper.toVo(transformEntity);
} catch (Exception e) {
MemoryLogger.error("TransformJdbcDao | transform rule load error - " + e.getMessage(), e);
logger.error("TransformJdbcDao | transform rule load error - " + e.getMessage(), e);
}
return transform;
}
public Transform findTransformByName(String transformName) {
TransformEntity transformEntity = transformLoader.getById(transformName);
Stream<String> layoutNames = transformEntity.getTransformTypeEntities().stream()
.map(transformTypeEntity -> transformTypeEntity.getId().getLoutname());
layoutNames.forEach(layoutManager::reload);
return transformEntityMapper.toVo(transformEntity);
}
}
@@ -0,0 +1,159 @@
package com.eactive.eai.transformer.engine;
import java.io.Serializable;
import org.nfunk.jep.JEP;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.function.FunctionDefinition;
import com.eactive.eai.transformer.function.FunctionManager;
import com.eactive.eai.transformer.function.crypto.Decrypt;
import com.eactive.eai.transformer.function.crypto.Des3Decrypt;
import com.eactive.eai.transformer.function.crypto.Des3Encrypt;
import com.eactive.eai.transformer.function.crypto.DesDecrypt;
import com.eactive.eai.transformer.function.crypto.DesEncrypt;
import com.eactive.eai.transformer.function.crypto.Encrypt;
import com.eactive.eai.transformer.function.crypto.Seed128Decrypt;
import com.eactive.eai.transformer.function.crypto.Seed128Encrypt;
import com.eactive.eai.transformer.function.crypto.SeedDecrypt;
import com.eactive.eai.transformer.function.crypto.SeedEncrypt;
import com.eactive.eai.transformer.function.generic.ToBytes;
import com.eactive.eai.transformer.util.Logger;
public class Parser implements Serializable {
private static final long serialVersionUID = -3657522834962737552L;
private static Logger logger = Logger.getLogger("transformer");
private transient JEP jep = new JEP(); // Create a new parser
public Parser() {
getJep().addStandardFunctions();
getJep().addStandardConstants();
getJep().setImplicitMul(true);
getJep().setAllowAssignment(true);
getJep().setAllowUndeclared(true);
try {
addGenericFunctions();
} catch (Exception e) {
logger.error("Parser | error when add generic function", e);
}
}
public void parse(String expr) throws Exception {
getJep().parseExpression(expr);
if (getJep().hasError()) {
throw new Exception("[Parser] Error when parsing expr : " + getJep().getErrorInfo());
}
}
public void addVariable(String name, double value) throws Exception {
getJep().addVariable(name, value);
if (getJep().hasError()) {
throw new Exception("[Parser] Error when parsing double : " + getJep().getErrorInfo());
}
}
public void addVariable(String name, Object value) throws Exception {
getJep().addVariable(name, value);
if (getJep().hasError()) {
throw new Exception("[Parser] Error when parsing Object : " + getJep().getErrorInfo());
}
}
public double getValue() throws Exception {
double value = getJep().getValue();
if (getJep().hasError()) {
throw new Exception("[Parser] Error during evaluation : " + getJep().getErrorInfo());
}
return value;
}
public Object getValueAsObject() throws Exception {
Object value = getJep().getValueAsObject();
if (getJep().hasError()) {
throw new Exception("[Parser] Error during evaluation - error info : [" + getJep().getErrorInfo() + "]");
}
return value;
}
public void initSymbolTable() {
getJep().initSymTab();
}
@SuppressWarnings("unchecked")
public String[] getSymbols() {
String[] symbols = new String[getJep().getSymbolTable().size()];
symbols = (String[])getJep().getSymbolTable().keySet().toArray(new String[symbols.length]);
return symbols;
}
private void addGenericFunctions() throws Exception {
FunctionManager manager = FunctionManager.getInstance();
String [] funcName = manager.getAllFunctionNames();
int size = funcName.length;
FunctionDefinition funcDef = null;
PostfixMathCommand command = null;
for( int i = 0; i < size; i++) {
funcDef = manager.getFunctionDefinition(funcName[i]);
if (funcDef == null) continue;
String functionClass = funcDef.getFunctionClass();
if (functionClass == null) continue;
if(!functionClass.startsWith("com.eactive.eai.transformer.function")) {
continue;
}
// 등록된 함수의 실제 Class가 없는 경우 Skip 한다.
try {
command = (PostfixMathCommand) Class.forName(functionClass).newInstance();
} catch (Exception e ) {
continue;
}
try{
addFunction(funcName[i], command);
}catch (Exception e ) {
throw new Exception("[Parser] Error during addGenericfunction : " + getJep().getErrorInfo());
}
}
addFunction("tobytes", new ToBytes());
addFunction("encrypt", new Encrypt());
addFunction("decrypt", new Decrypt());
addFunction("des_encrypt", new DesEncrypt());
addFunction("des_decrypt", new DesDecrypt());
addFunction("des3_encrypt", new Des3Encrypt());
addFunction("des3_decrypt", new Des3Decrypt());
addFunction("seed_encrypt", new SeedEncrypt());
addFunction("seed_decrypt", new SeedDecrypt());
addFunction("seed128_encrypt", new Seed128Encrypt());
addFunction("seed128_decrypt", new Seed128Decrypt());
}
private void addFunction(String name, PostfixMathCommand command) {
if(name == null || command == null) {
logger.warn("addFunction ("+name+","+command+") skip null");
return;
}
getJep().addFunction(name.toUpperCase(), command);
getJep().addFunction(name.toLowerCase(), command);
}
public JEP getJep() {
return jep;
}
public void setJep(JEP jep) {
this.jep = jep;
}
}
@@ -0,0 +1,77 @@
package com.eactive.eai.transformer.engine;
import java.time.Duration;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import com.eactive.eai.transformer.SystemKeys;
import com.eactive.eai.transformer.util.Logger;
public class ParserFactory {
private static Logger logger = Logger.getLogger("transformer");
static ObjectPool<Parser> parserPool;
// MAX concurrent size
static int maxSize = 10000;
static {
try {
maxSize = Integer.parseInt(System.getProperty(SystemKeys.TRANSFROMER_PARSER_CACHE_SIZE, SystemKeys.TRANSFROMER_PARSER_CACHE_DEFAULT));
} catch(Exception e) {
maxSize = Integer.parseInt(SystemKeys.TRANSFROMER_PARSER_CACHE_DEFAULT);
}
logger.warn(">> ParserFactory init config");
logger.warn(String.format("%s = %s", SystemKeys.TRANSFROMER_PARSER_CACHE_SIZE, maxSize));
ParserObjectFactory pFactory = new ParserObjectFactory();
GenericObjectPoolConfig<Parser> config = new GenericObjectPoolConfig<>();
config.setMaxTotal(maxSize);
config.setMaxWait(Duration.ofSeconds(3));
config.setMaxIdle(maxSize);
config.setMinIdle(0);
parserPool = new GenericObjectPool<>(pFactory, config);
}
private ParserFactory() {
}
public static int getPoolMaxSize() {
return maxSize;
}
public static synchronized Parser getParser() throws Exception {
return parserPool.borrowObject();
}
public static synchronized void putParser(Parser parser) throws Exception {
parser.initSymbolTable();
parserPool.returnObject(parser);
}
public static int activeCount() {
return parserPool.getNumActive();
}
}
class ParserObjectFactory extends BasePooledObjectFactory<Parser> {
@Override
public Parser create() throws Exception {
Parser parser = new Parser();
parser.initSymbolTable();
return parser;
}
@Override
public PooledObject<Parser> wrap(Parser obj) {
return new DefaultPooledObject<>(obj);
}
}
@@ -0,0 +1,114 @@
package com.eactive.eai.transformer.engine;
import org.springframework.stereotype.Component;
import com.eactive.eai.common.lifecycle.Lifecycle;
import com.eactive.eai.common.lifecycle.LifecycleException;
import com.eactive.eai.common.lifecycle.LifecycleListener;
import com.eactive.eai.common.lifecycle.LifecycleSupport;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.transformer.function.FunctionManager;
import com.eactive.eai.transformer.layout.LayoutManager;
import com.eactive.eai.transformer.layout.LayoutTypeManager;
import com.eactive.eai.transformer.transform.TransformManager;
import com.eactive.eai.transformer.util.Logger;
@Component
public class TransformEngine implements Lifecycle {
private static Logger logger = Logger.getLogger("transformer");
private Transformer transformer;
private LifecycleSupport lifecycleSupport = null;
private boolean started;
private TransformEngine() {
lifecycleSupport = new LifecycleSupport(this);
transformer = new Transformer();
}
private void initEngine() throws LifecycleException {
Runtime runtime = Runtime.getRuntime();
long memUnit = 1024;
logger.info("INIT Usage("+memUnit+") : "+ (runtime.totalMemory() - runtime.freeMemory())/memUnit + " / " +runtime.totalMemory()/memUnit);
FunctionManager.getInstance().start();
logger.info("FUNC Usage("+memUnit+") : "+ (runtime.totalMemory() - runtime.freeMemory())/memUnit + " / " +runtime.totalMemory()/memUnit);
LayoutTypeManager.getInstance().start();
logger.info("LTYP Usage("+memUnit+") : "+ (runtime.totalMemory() - runtime.freeMemory())/memUnit + " / " +runtime.totalMemory()/memUnit);
LayoutManager.getManager().start();
logger.info("LOUT Usage("+memUnit+") : "+ (runtime.totalMemory() - runtime.freeMemory())/memUnit + " / " +runtime.totalMemory()/memUnit);
TransformManager.getManager().start();
logger.info("TRAN Usage("+memUnit+") : "+ (runtime.totalMemory() - runtime.freeMemory())/memUnit + " / " +runtime.totalMemory()/memUnit);
ParserFactory.activeCount();
}
private void clearEngine() throws LifecycleException {
LayoutTypeManager.getInstance().stop();
FunctionManager.getInstance().stop();
LayoutManager.getManager().stop();
TransformManager.getManager().stop();
}
public static TransformEngine getInstance() {
return ApplicationContextProvider.getContext().getBean(TransformEngine.class);
}
/**
* 변환 처리용 인스턴스를 가져옴.
*/
public Transformer getTransformer() {
return transformer;
}
public void addLifecycleListener(LifecycleListener listener) {
lifecycleSupport.addLifecycleListener(listener);
}
public LifecycleListener[] findLifecycleListeners() {
return lifecycleSupport.findLifecycleListeners();
}
public void removeLifecycleListener(LifecycleListener listener) {
lifecycleSupport.removeLifecycleListener(listener);
}
public void start() throws LifecycleException {
if (isStarted())
return;
try {
initEngine();
this.started = true;
} catch (LifecycleException e) {
throw e;
} catch (Exception e) {
throw new LifecycleException(e);
}
}
public boolean isStarted() {
return this.started;
}
public void stop() throws LifecycleException {
try {
clearEngine();
this.started = false;
} catch (LifecycleException e) {
throw e;
} catch (Exception e) {
throw new LifecycleException(e);
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(FunctionManager.getInstance().toString() + "\n");
sb.append(LayoutTypeManager.getInstance().toString() + "\n");
sb.append(LayoutManager.getManager().toString() + "\n");
sb.append(TransformManager.getManager().toString());
return sb.toString();
}
}
@@ -0,0 +1,66 @@
package com.eactive.eai.transformer.engine;
import com.eactive.eai.transformer.TransformerException;
import com.eactive.eai.transformer.message.Message;
public class TransformException extends TransformerException {
private String transformName;
private Message resultMessage;
private Message[] sourceMessages;
private TransformOption option;
public TransformException(String message, String transformName,
Message resultMessage, Message[] sourceMessages, TransformOption option) {
this(message, transformName, resultMessage, sourceMessages, option, null);
}
public TransformException(String message, String transformName,
Message resultMessage, Message[] sourceMessages,
TransformOption option, Throwable cause) {
super(message, cause);
this.transformName = transformName;
this.resultMessage = resultMessage;
this.sourceMessages = sourceMessages;
this.option = option;
}
public String getTransformName() {
return transformName;
}
public boolean hasResultMessage() {
return (resultMessage != null);
}
public Message getResultMessage() {
return resultMessage;
}
public Message[] getSourceMessages() {
return sourceMessages;
}
public boolean hasTransformOption() {
return (option != null);
}
public TransformOption getTransformOption() {
return option;
}
@Override
public String getMessage() {
StringBuilder sb = new StringBuilder();
sb.append("\n전문레이아웃매핑=" + transformName);
sb.append(", 원천전문레이아웃=");
for (int i=0; i<sourceMessages.length; i++) {
sb.append("|" + sourceMessages[i].getName());
}
if (resultMessage != null) {
sb.append(", 타겟전문레이아웃=" + resultMessage.getName());
}
sb.append(super.getMessage());
return sb.toString();
}
}
@@ -0,0 +1,80 @@
package com.eactive.eai.transformer.engine;
// util imports:
import java.util.HashMap;
import java.util.Map;
public class TransformOption {
/**
* 변환 결과 메시지를 제공할 경우 참조되며 버퍼를 사용할 것인지 결정할 수 있는 boolean값.
* 만약 버퍼를 사용 안했을 경우 메공된 변환 결과 메시지가 비정상적으로 변경될 경우가 있음.
* 기본값은 true.
*/
public static final String OPTION_BUFFERED = "BUFFERED";
/**
* 레이이웃에 정의된 기본값 사용하여 결과 메시지 생성시 적용할 것인지 결정하는 boolean값.
* 기본값은 false.
*/
public static final String OPTION_USE_DEFAULT = "USE_DEFAULT";
public static final TransformOption DEFAULT_OPTION;
static {
DEFAULT_OPTION = new TransformOption();
DEFAULT_OPTION.setBoolean(OPTION_BUFFERED, true);
DEFAULT_OPTION.setBoolean(OPTION_USE_DEFAULT, false);
}
private Map optionMap;
public TransformOption() {
optionMap = new HashMap();
}
public void setString(String key, String value) {
optionMap.put(key, value);
}
public void setInt(String key, int value) {
optionMap.put(key, new Integer(value));
}
public void setBoolean(String key, boolean value) {
optionMap.put(key, new Boolean(value));
}
public String getString(String key) {
return (String) optionMap.get(key);
}
/**
* 값이 없을 경우는 0
*/
public int getInt(String key) {
if(optionMap.get(key) == null) {
return 0;
}
else {
return (optionMap.containsKey(key)
? ((Integer) optionMap.get(key)).intValue() : 0);
}
}
/**
* 값이 없을 경우는 false.
*/
public boolean getBoolean(String key) {
// return (optionMap.containsKey(key)? ((Boolean) optionMap.get(key)).booleanValue() : false);
Object obj = optionMap.get(key);
if(obj == null) {
return false;
}
else {
return ((Boolean) optionMap.get(key)).booleanValue();
}
}
}
@@ -0,0 +1,60 @@
package com.eactive.eai.transformer.engine;
import java.util.ArrayList;
import java.util.List;
import com.eactive.eai.transformer.message.Message;
public class TransformResult {
private List warningList;
private Message resultMessage;
private Message[] sourceMessages;
private TransformOption option;
TransformResult() {
}
public boolean hasWarning() {
return (warningList != null);
}
public List getWarningList() {
return warningList;
}
void addWarning(TransformWarning warning) {
if (warningList == null) {
warningList = new ArrayList();
}
warningList.add(warning);
}
public Object getResultData() throws Exception {
return resultMessage.getData();
}
public Message getResultMessage() {
return resultMessage;
}
void setResultMessage(Message message) {
this.resultMessage = message;
}
public Message[] getSourceMessages() {
return sourceMessages;
}
void setSourceMessages(Message[] messages) {
this.sourceMessages = messages;
}
public TransformOption getOption() {
return option;
}
void setTransformOption(TransformOption option) {
this.option = option;
}
}
@@ -0,0 +1,30 @@
package com.eactive.eai.transformer.engine;
public class TransformWarning {
private String warningCode;
private String warningInfo;
private Throwable cause;
public TransformWarning(String warningCode, String warningInfo) {
this(warningCode, warningInfo, null);
}
public TransformWarning(String warningCode, String warningInfo,
Throwable cause) {
this.warningCode = warningCode;
this.warningInfo = warningInfo;
this.cause = cause;
}
public String getWarningCode() {
return warningCode;
}
public String getWarningInfo() {
return warningInfo;
}
public Throwable getCause() {
return cause;
}
}
@@ -0,0 +1,721 @@
package com.eactive.eai.transformer.engine;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.eactive.eai.transformer.TransformerException;
import com.eactive.eai.transformer.layout.Item;
import com.eactive.eai.transformer.layout.Layout;
import com.eactive.eai.transformer.layout.LayoutInitializationException;
import com.eactive.eai.transformer.layout.LayoutNotFoundException;
import com.eactive.eai.transformer.layout.Types;
import com.eactive.eai.transformer.message.ISO8583Message;
import com.eactive.eai.transformer.message.InvalidAccessException;
import com.eactive.eai.transformer.message.Message;
import com.eactive.eai.transformer.message.MessageFactory;
import com.eactive.eai.transformer.transform.Transform;
import com.eactive.eai.transformer.transform.TransformItem;
import com.eactive.eai.transformer.transform.TransformManager;
import com.eactive.eai.transformer.util.HexUtil;
import com.eactive.eai.transformer.util.Logger;
import com.eactive.eai.transformer.util.MemoryLogger;
import com.eactive.eai.transformer.util.StringUtil;
/**
* 변환 룰에 맞춰서 메시지를 변환하는 기능을 제공한다.
*/
public class Transformer {
private static Logger logger = Logger.getLogger("transformer");
public static final int INDEX_RESULT = -1;
public static final int INDEX_QUEUE = -2;
public static final int SINGLE_MAPPING = -1;
public static final int DYNAMIC_MAPPING = -2;
// transformLine 함수에서 [*] 형태가 존재할 경우 -> 각 item 별 실행
static char[] findChars = {'(', '+', ' '};
private static boolean isSimpleInstruction(String message) {
if(message.charAt(message.length()-1) == ')') return false;
for(int i=0; i<findChars.length; i++) {
if(message.indexOf(findChars[i]) > -1) {
return false;
}
}
return true;
}
Transformer() {
}
private static final char[] FUNCTION_SEPARATORS = { ' ', ',' };
/**
* Column 구분자 '[*]'를 index 값으로 변경해주는 메소드
* 함수구분자 ' ', 혹은 ',' 별 첫번째 * 만 변경한다.
*
* 예제>
* 호줄 : replaceAsteriskToIndex("(abc[*].d*ef[*].ghi*) + (*jk[*].lm[*].no)", 12);
* 결과 : (abc[12].d*ef[*].ghi*) + (*jk[12].lm[*].no)
*
* @param src 대상 문자열
* @param index 변경할 index 값
* @return 결과값
*/
private static String replaceAsteriskToIndex(String src, int idx) {
String index = Integer.toString(idx);
char[] orgChars = src.toCharArray();
char[] settingChars = index.toCharArray();
StringBuilder sb = new StringBuilder(orgChars.length);
boolean doChange = true;
boolean isChanged = false;
for(int i = 0; i < orgChars.length;i++) {
char c = orgChars[i];
if (doChange && c == '*'
&& i - 1 > -1 && i + 1 < orgChars.length
&& orgChars[i - 1] == '[' && orgChars[i + 1] == ']' ) {
isChanged = true;
doChange = false;
for (char settingChar : settingChars) {
sb.append(settingChar);
}
} else {
sb.append(c);
}
for(char functionSeparator : FUNCTION_SEPARATORS){
if(c == functionSeparator) {
doChange = true;
break;
}
}
}
if(!isChanged) {
throw new NullPointerException("변환인자 '[*]' 가 존재하지 않습니다. - "+src);
}
return sb.toString();
}
/**
* 변환 메소드 (변환 결과 메시지는 자동 생성).
* transformName을 이용해서 어떠한 변환룰을 적용할지 결정됨.
* TransformOption이 null일 경우 기본값을 사용함.
* 운본 메시지를 생성하지 않고 데이터만 전달, 내부적으로 Message를 생성해서 사용됨.
* @see Message
* @see TransformOption
*/
public TransformResult transform(String transformName,
Object[] sourceDatas, TransformOption option)
throws TransformerException {
Transform tr = TransformManager.getManager().getTransform(transformName);
Message[] sourceMessages = new Message[sourceDatas.length];
try {
for (int i = 0; i < sourceDatas.length; i++) {
Layout layout = tr.getSourceLayout(i);
sourceMessages[i] = MessageFactory.getFactory().getMessage(layout.getName());
sourceMessages[i].setData(sourceDatas[i]);
}
} catch (Exception e) {
throw new TransformException("error when set data. - " + e.getMessage(),
transformName,
null,
sourceMessages,
option, e);
}
return transform(transformName, null, sourceMessages, option);
}
/**
* 변환 메소드 (변환 결과 메시지는 자동 생성).
* transformName을 이용해서 어떠한 변환룰을 적용할지 결정됨.
* TransformOption이 null일 경우 기본값을 사용함.
* @see Message
* @see TransformOption
*/
public Message transform(String transformName, Message[] sourceMessages)
throws TransformerException {
TransformResult result = transform(transformName, null, sourceMessages,
null);
return result.getResultMessage();
}
/**
* 변환 메소드 (변환 결과 메시지는 자동 생성).
* transformName을 이용해서 어떠한 변환룰을 적용할지 결정됨.
* TransformOption이 null일 경우 기본값을 사용함.
* @see Message
* @see TransformOption
*/
public TransformResult transform(String transformName,
Message[] sourceMessages, TransformOption option)
throws TransformerException {
return transform(transformName, null, sourceMessages, option);
}
/**
* 변환 메소드 (변환 결과 메시지는 자동 생성).
* transformName을 이용해서 어떠한 변환룰을 적용할지 결정됨.
* TransformOption이 null일 경우 기본값을 사용함.
* @see Message
* @see TransformOption
*/
public TransformResult transform(String transformName,
Message targetMessage, Message[] sourceMessages)
throws TransformerException {
return transform(transformName, targetMessage, sourceMessages, null);
}
/**
* 변환 메소드 (변환 결과 메시지 제공).
* transformName을 이용해서 어떠한 변환룰을 적용할지 결정됨.
* TransformOption이 null일 경우 기본값을 사용함.
* @see Message
* @see TransformOption
*/
public TransformResult transform(String transformName,
Message targetMessage, Message[] sourceMessages, TransformOption option)
throws TransformerException {
List<String> errors = new ArrayList<String>();
try {
/**
* [1] 변환 정보 조회
*/
Transform transform = TransformManager.getManager().getTransform(transformName);
if (transform == null) {
throw new TransformException("Failed to look up this conversion rule. - " +
transformName, transformName, targetMessage, sourceMessages, option);
} else if (transform.getSourceLayoutCount() != sourceMessages.length) {
throw new TransformException("The number of parameter messages specified in the conversion rule does not match the number of parameters provided.["+transform.getSourceLayoutCount()
+","+sourceMessages.length+"]",
transformName, targetMessage, sourceMessages, option);
}
/**
* [2] 소스 메시지 내용 유효성 확인
*/
try {
checkValidSourceMessages(transform, sourceMessages);
} catch (Exception e) {
throw new TransformException("Invalid original message. : " + e.getMessage(),
transformName,
targetMessage,
sourceMessages,
option, e);
}
/**
* [3] 변환 옵션이 제공 안되었을 경우 기본 옵션을 할당
*/
if (option == null) {
option = TransformOption.DEFAULT_OPTION;
}
/**
* [4] 결과 메시지가 null 이라면 생성
*/
if (targetMessage == null) {
try {
targetMessage = MessageFactory.getFactory().getMessage(transform.getTargetLayout().getName());
} catch (LayoutNotFoundException e) {
throw new TransformException("target message not found.",
transformName,
targetMessage,
sourceMessages,
option, e);
} catch (LayoutInitializationException e) {
throw new TransformException("target message init failed.",
transformName,
targetMessage,
sourceMessages,
option, e);
} catch(Exception e) {
throw new TransformException(e.getMessage(),
transformName,
targetMessage,
sourceMessages,
option, e);
}
}
/**
* [5] 변환 룰에 정의된 명령 수행
*/
for (Iterator<?> itr = transform.getTransformItemList().iterator(); itr.hasNext();) {
TransformItem transformItem = (TransformItem) itr.next();
transformLine(transformItem, targetMessage, sourceMessages, option, errors);
}
if (targetMessage instanceof ISO8583Message) {
((ISO8583Message) targetMessage).assembleDataBytes();
}
TransformResult transformResult = new TransformResult();
transformResult.setSourceMessages(sourceMessages);
transformResult.setResultMessage(targetMessage);
transformResult.setTransformOption(option);
if (!errors.isEmpty() && (logger.isWarnEnabled())) {
StringBuilder sb = new StringBuilder();
sb.append("Transformer | transform error - \n");
for (Iterator<String> iter = errors.iterator(); iter.hasNext();) {
sb.append(iter.next());
if (iter.hasNext()) {
sb.append("\n");
}
}
String msg = transformName + " | " + sb.toString();
logger.warn(msg);
MemoryLogger.error("<WARN> " + msg);
}
return transformResult;
} catch(TransformerException e) {
logger.error("", e);
throw e;
}
}
/**
* transform item - line(record) 단위의 작업
*/
protected void transformLine(TransformItem transformItem, Message targetMessage,
Message[] sourceMessages, TransformOption option, List<String> errors)
throws TransformerException {
Item resultItem = null;
String resultItemPath = transformItem.getResultItemPath();
String instruction = transformItem.getInstruction();
/**
* 좌항 또는 우항이 빈 공백일 경우 (excel 경우 발생)
*/
if ("".equals(resultItemPath.trim()) || "".equals(instruction))
return;
/**
* data target기준 copy (예외처리한거임 ) JUN ADD
*/
if (instruction.indexOf("DATACOPY") >= 0){
if ( sourceMessages[0].getData() instanceof byte[] ){
if (sourceMessages[0].getLength() > targetMessage.getLength() ){
byte [] src = (byte[])sourceMessages[0].getData();
ByteBuffer bb = ByteBuffer.allocate(sourceMessages[0].getLength());
bb.put(src);
byte [] dst = new byte[targetMessage.getLength()];
bb.flip();
bb.get(dst, 0, dst.length);
targetMessage.setData(dst);
}else if (sourceMessages[0].getLength() < targetMessage.getLength() ){
byte [] src = (byte[])sourceMessages[0].getData();
ByteBuffer bb = ByteBuffer.allocate(targetMessage.getLength());
bb.put(src);
for (int i=src.length;i < targetMessage.getLength();i++ ){
bb.put(" ".getBytes());
}
byte [] dst = new byte[targetMessage.getLength()];
bb.flip();
bb.get(dst, 0, dst.length);
targetMessage.setData(dst);
}else{
targetMessage.setData(sourceMessages[0].getData());
}
}else if ( sourceMessages[0].getData() instanceof String ){
if (sourceMessages[0].getLength() > targetMessage.getLength() ){
String src = (String)sourceMessages[0].getData();
targetMessage.setData(src.substring(0,targetMessage.getLength()));
}else if (sourceMessages[0].getLength() < targetMessage.getLength() ){
String src = (String)sourceMessages[0].getData();
String dst ="";
for (int i=src.length() ;i < targetMessage.getLength();i++ ){
dst = dst + " ";
}
targetMessage.setData(src + dst);
}else{
targetMessage.setData(sourceMessages[0].getData());
}
}
return;
}
/**
* item[*] 형태일 경우
*/
int idx = StringUtil.isMulti(instruction);
if (idx > 0) {
String prefix = instruction.substring(0, idx);
int p = StringUtil.findStart(prefix);
if (p > 0) {
prefix = instruction.substring(p+1, idx) + "[-1]";
}
// occurance 가 * (0, 1, ...) 경우 에러 수정 :2009.04.20
else {
prefix = prefix + "[-1]";
}
Item item = null;
for (int i = 0; i < sourceMessages.length; i++) {
try {
item = ((Item) sourceMessages[i]).getItem(prefix, true);
if (item != null) {
break;
}
} catch (Exception e) {
; // do nothing
}
}
if (item == null) {
errors.add(" Expression : " + transformItem.getResultItemPath() +
" = " + transformItem.getInstruction() +
" | Item (" + prefix + ")can not be found in Source Message. Check conversion rules - ");
for (int i = 0; i < sourceMessages.length; i++) {
errors.add(sourceMessages[i].toString());
}
return;
}
int count = item.arraySize();
for (int i = 0; i < count; i++) {
TransformItem trItem = new TransformItem();
trItem.setTransform(transformItem.getTransform());
trItem.setInstruction(replaceAsteriskToIndex(instruction, i ));
trItem.setResultItemPath(replaceAsteriskToIndex(resultItemPath, i ));
transformLine(trItem, targetMessage, sourceMessages, option, errors);
}
return;
}
/**
* result item 설정
*/
String itemPath = transformItem.getResultItemPath();
/**
* result item path 가 message 명으로 시작하지 않을 경우 -> 메시지명을 앞에 붙여준다.
*/
// FIXME : 정상적으로 등록되었다면 불필요한 로직임
// if (!itemPath.startsWith(transformItem.getTransform().getTargetLayout().getName())) {
// itemPath = transformItem.getTransform().getTargetLayout().getName() + Types.FIELD_SEPARATOR + itemPath;
// }
resultItem = ((Item) targetMessage).getOrCreateItem(itemPath, true);
if (resultItem == null) {
errors.add(" Expression : " + transformItem.getResultItemPath() +
" = " + transformItem.getInstruction() +
" | Item (" + itemPath + ") can not be found in Target Message. Check conversion rules - ");
errors.add(targetMessage.toString());
return;
}
/**
*
* 1. field|attribute : transform 을 바로 진행한다. (transformEach)
* 2. group|message : 아래의 sub 구성 요소로 분리하여 transformLine을 재귀 호출한다.
* attribute : for test of kesa xml attribute type (DHLEE)
*/
if (resultItem.isField() || resultItem.isAttr()) {
/**
* 튜닝 - Instruction(Expression) 이 Simple할 경우 JEP Parsing을 할 필요가 없다.
*/
if ( isSimpleInstruction(transformItem.getInstruction().trim()) ) {
transformAtomWithoutParsing(transformItem, targetMessage, sourceMessages, option, errors);
} else {
transformAtom(transformItem, targetMessage, sourceMessages, option, errors);
}
} else {
Parser parser = null;
try {
parser = ParserFactory.getParser();
Item item = null;
try {
parser.parse(transformItem.getInstruction());
} catch (Exception e) {
logger.error("[Transformer] Expression : " +
transformItem.getResultItemPath() + " = " +
transformItem.getInstruction(), e);
throw new TransformException("Error during parse instruction : " + e.getMessage(),
transformItem.getResultItemPath() + " = " + transformItem.getInstruction(),
targetMessage,
sourceMessages,
option, e);
}
String[] symbols = parser.getSymbols();
String sourceItemPath = null;
if (symbols.length > 0) {
sourceItemPath = symbols[0];
for (int i = 0; i < sourceMessages.length; i++) {
try {
item = ((Item) sourceMessages[i]).getItem(sourceItemPath, true);
if (item != null) {
break;
}
} catch (Exception e) {
}
}
}
if (item == null) {
throw new TransformException("I can not do conversion work. Please check the conversion rules. Expression : ",
transformItem.getResultItemPath() + " = " + transformItem.getInstruction(),
targetMessage,
sourceMessages,
option, null);
}
if (item.isField() || item.isAttr()) {
// set value to Group
if ( isSimpleInstruction(transformItem.getInstruction().trim()) ) {
transformAtomWithoutParsing(transformItem, targetMessage, sourceMessages, option, errors);
} else {
transformAtom(transformItem, targetMessage, sourceMessages, option, errors);
}
return;
}
List<Item> children = item.getChildList();
for (int i = 0; i < children.size(); i++) {
Item child = (Item) children.get(i);
if (child.getIndex() < 0) {
continue;
}
TransformItem trItem = new TransformItem();
trItem.setTransform(transformItem.getTransform());
trItem.setResultItemPath(transformItem.getResultItemPath().replace(
transformItem.getResultItemPath(),
transformItem.getResultItemPath() + Types.FIELD_SEPARATOR + child.getName() + "[" + child.getIndex() + "]"));
String sourceItemName = transformItem.getResultItemPath().replace(targetMessage.getName(), sourceMessages[0].getName());
trItem.setInstruction(transformItem.getInstruction().replace(
sourceItemName,
sourceItemName + Types.FIELD_SEPARATOR + child.getName() + "[" + child.getIndex() + "]"));
transformLine(trItem, targetMessage, sourceMessages, option, errors);
}
} catch (Exception e) {
throw new TransformException(e.getMessage(), null, targetMessage, sourceMessages, option, e);
} finally {
if (parser != null)
try {
ParserFactory.putParser(parser);
} catch(Exception e) {}
}
}
}
protected void transformAtom(TransformItem transformItem, Message targetMessage, Message[] sourceMessages
, TransformOption option, List<String> errors)
throws TransformerException {
Parser parser = null;
try {
/**
* [1] parse expression
*/
parser = ParserFactory.getParser();
try {
parser.parse(transformItem.getInstruction());
} catch (Exception e) {
throw new TransformException("Error during parse instruction : " + e.getMessage(),
transformItem.getResultItemPath() + " = " + transformItem.getInstruction(),
targetMessage,
sourceMessages,
option, e);
}
Object value = null;
String[] symbols = parser.getSymbols();
for (int i = 0; i < symbols.length; i++) {
for (int j = 0; j < sourceMessages.length; j++) {
try {
/**
* transformItem 에 default value 가 설정되어 있다면
*/
if (symbols[i].equals("DEFAULT_VALUE") && (transformItem.getDefaultValue() != null)) {
value = transformItem.getDefaultValue();
if (((String) value).startsWith("0x") || ((String) value).startsWith("0X")) {
value = HexUtil.hex2bytes((String) value);
}
} else {
try {
if (symbols[i].startsWith(sourceMessages[j].getName())) {
value = sourceMessages[j].getObject(symbols[i]);
} else {
if (sourceMessages.length == 1) {
value = sourceMessages[j].getObject(symbols[i]);
} else {
continue;
}
}
} catch(InvalidAccessException e) {
errors.add("Transformer | ITEM Error during conversion (source message) - Continue - " + e.getMessage());
continue;
}
}
parser.addVariable(symbols[i], value);
break;
} catch (Exception e) {
errors.add("Transformer | " + e.getMessage() + " | " + transformItem.toString());
}
}
}
/**
* [2] check (evaluated) value
*/
if ((value == null) && (symbols.length > 0)) {
if(logger.isDebugEnabled()) {
String msg = "[WARN] Transformer | cannot assign null value to right-hand side of expression, " +
"check if item is composite(messsage or group) - " + transformItem.toString();
logger.debug(msg);
MemoryLogger.txlog(msg);
}
return;
}
Object result = null;
try {
result = parser.getValueAsObject();
} catch (Exception e) {
throw new TransformException("Error during evaluate : " + e.getMessage(),
transformItem.getResultItemPath() + " = " + transformItem.getInstruction(),
targetMessage,
sourceMessages,
option, e);
}
/**
* [3] set result to targetMessage
*/
try {
targetMessage.setObject(transformItem.getResultItemPath(), result);
} catch (Exception e) {
throw new TransformException(
"An error occurred when setting conversion data to result message. - " + e.getMessage(),
transformItem.getResultItemPath() + " = " + transformItem.getInstruction(),
targetMessage,
sourceMessages,
option, e);
}
} catch(Exception e) {
throw new TransformException("Error occurred during conversion : " + e.getMessage(),
transformItem.getResultItemPath() + " = " +
transformItem.getInstruction(),
targetMessage,
sourceMessages,
option, e);
} finally {
if (parser != null)
try {
ParserFactory.putParser(parser);
} catch(Exception e) {}
}
}
/**
* instruction 이 simple 할 경우 (JEP Parsing 단계를 skip한다)
* 1. message...field | message...attribute 일 경우
* 2. 상수일 경우
* 3. default value 일 경우
*/
protected void transformAtomWithoutParsing(TransformItem transformItem, Message targetMessage, Message[] sourceMessages
, TransformOption option, List<String> errors)
throws TransformerException {
String instruction = transformItem.getInstruction().trim();
Object value = null;
boolean findSource = true;
for (int j = 0; j < sourceMessages.length; j++) {
try {
/**
* transformItem 에 default value 가 설정되어 있다면
*/
if (instruction.equals("DEFAULT_VALUE") && (transformItem.getDefaultValue() != null)) {
value = transformItem.getDefaultValue();
if (((String) value).startsWith("0x") || ((String) value).startsWith("0X")) {
value = HexUtil.hex2bytes((String) value);
}
} else {
try {
if (instruction.startsWith(sourceMessages[j].getName())) {
value = sourceMessages[j].getObject(instruction);
} else {
if (sourceMessages.length == 1) {
value = sourceMessages[j].getObject(instruction);
} else {
continue;
}
}
} catch(InvalidAccessException e) {
e.printStackTrace();
errors.add("Transformer] ITEM Error during conversion (source message access) - continue- " + e.getMessage());
value ="";
findSource = false;
continue;
}
}
break;
} catch (Exception e) {
if(logger.isWarnEnabled()) {
logger.warn("[Transformer] " + e.getMessage() +
" | Expression : " + transformItem.getResultItemPath() +
" = " + transformItem.getInstruction());
}
}
}
try {
// FIX-ME : 소스메시지를 찾은 경우에만 설정하도록 함
if(findSource) targetMessage.setObject(transformItem.getResultItemPath(), value);
} catch (Exception e) {
throw new TransformException(
"An error occurred when setting conversion data to result message. - " + e.getMessage(),
transformItem.getResultItemPath() + " = " + transformItem.getInstruction(),
targetMessage,
sourceMessages,
option, e);
}
}
private void checkValidSourceMessages(Transform transform,
Message[] messages) throws Exception {
if (messages == null) {
throw new Exception("Source Message is null.");
}
for (int i = 0; i < messages.length; i++) {
if (messages[i] == null) {
throw new Exception("Source Message["+i+"] is null.");
}
Layout layout = transform.getSourceLayout(((Item) messages[i]).getName());
if (layout == null) {
throw new Exception("Source Message <" + ((Item) messages[i]).getName() +
">is a message that is not defined in transform <" + transform.getName() + ">.");
}
}
}
}
@@ -0,0 +1,27 @@
package com.eactive.eai.transformer.function;
public class ExecutionException extends Exception {
private Object[] parameters;
public ExecutionException(String message, Object[] parameters) {
this(message, parameters, null);
}
public ExecutionException(String message, Object[] parameters,
Throwable cause) {
super(message, cause);
this.parameters = parameters;
}
public boolean hasParameters() {
return parameters != null;
}
public int getParameterLength() {
return parameters.length;
}
public Object[] getParameters() {
return parameters;
}
}
@@ -0,0 +1,12 @@
package com.eactive.eai.transformer.function;
public interface Function {
public static final int TYPE_BUILTIN = 2300;
public static final int TYPE_PRIMITIVE = 2301;
public static final int TYPE_GENERIC = 2302;
public static final int TYPE_CONVERT = 2303;
public static final int TYPE_USERDEFINED = 2304;
public Object execute(Object[] parameters) throws ExecutionException;
}
@@ -0,0 +1,98 @@
package com.eactive.eai.transformer.function;
import java.util.ArrayList;
import java.util.List;
import com.eactive.eai.transformer.dao.LoadingUnit;
public class FunctionDefinition extends LoadingUnit {
private static final long serialVersionUID = 1L;
private String name;
private String description;
private int returnTypeId;
private int functionTypeId;
private String functionClass;
private List<ParameterDefinition> parameterList;
public FunctionDefinition() {
parameterList = new ArrayList<>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getReturnTypeId() {
return returnTypeId;
}
public void setReturnTypeId(int returnTypeId) {
this.returnTypeId = returnTypeId;
}
public int getFunctionTypeId() {
return functionTypeId;
}
public void setFunctionTypeId(int functionTypeId) {
this.functionTypeId = functionTypeId;
}
public String getFunctionClass() {
return functionClass;
}
public void setFunctionClass(String functionClass) {
this.functionClass = functionClass;
}
public List<ParameterDefinition> getParameterList() {
return parameterList;
}
public void addParameter(ParameterDefinition parameter) {
parameterList.add(parameter);
}
public int getParameterCount() {
return parameterList.size();
}
public ParameterDefinition getParameter(int index) {
return parameterList.get(index);
}
public ParameterDefinition removeParameter(int index) {
return parameterList.remove(index);
}
public void setParameterList(List<ParameterDefinition> parameterList) {
this.parameterList = parameterList;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("FunctionDefinition[ name=").append(name);
sb.append(", description=").append(description);
sb.append(", returnTypeId=").append(returnTypeId);
sb.append(", functionTypeId=").append(functionTypeId);
sb.append(", functionClass=").append(functionClass);
sb.append(", parameterList=").append(parameterList);
sb.append(" ]");
return sb.toString();
}
}
@@ -0,0 +1,134 @@
package com.eactive.eai.transformer.function;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.eactive.eai.common.lifecycle.Lifecycle;
import com.eactive.eai.common.lifecycle.LifecycleException;
import com.eactive.eai.common.lifecycle.LifecycleListener;
import com.eactive.eai.common.lifecycle.LifecycleSupport;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.transformer.dao.FunctionDao;
import com.eactive.eai.transformer.util.Logger;
import com.eactive.eai.transformer.util.MemoryLogger;
@Component
public class FunctionManager implements Lifecycle {
protected static Logger logger = Logger.getLogger("transformer");
private Map<String, FunctionDefinition> functionMap;
private LifecycleSupport lifecycleSupport = null;
private boolean started;
@Autowired
private FunctionDao dao;
private FunctionManager() {
functionMap = new TreeMap<>();
lifecycleSupport = new LifecycleSupport(this);
}
public static FunctionManager getInstance() {
return ApplicationContextProvider.getContext().getBean(FunctionManager.class);
}
public synchronized void reload() {
init();
if (logger.isDebugEnabled()) {
logger.debug("FunctionManager | reloaded all functions");
}
}
public synchronized void reload(String functionName) {
FunctionDefinition functionDefinition = dao.findFunctionByName(functionName);
functionMap.put(functionName, functionDefinition);
if (logger.isDebugEnabled()) {
logger.debug("FunctionManager | reloaded function - " + functionName);
}
}
private void clear() {
functionMap.clear();
}
public FunctionDefinition getFunctionDefinition(String name) {
return functionMap.get(name);
}
public void remove(String functionName) {
functionMap.remove(functionName);
}
private void init() {
functionMap = dao.load();
logger.info("FunctionManager | all functions are initialized");
MemoryLogger.txlog("FunctionManager | all functions are initialized");
}
public void init(Map<String, FunctionDefinition> functionMap) {
this.functionMap = functionMap;
}
public void addLifecycleListener(LifecycleListener listener) {
lifecycleSupport.addLifecycleListener(listener);
}
public LifecycleListener[] findLifecycleListeners() {
return lifecycleSupport.findLifecycleListeners();
}
public void removeLifecycleListener(LifecycleListener listener) {
lifecycleSupport.removeLifecycleListener(listener);
}
public synchronized void start() throws LifecycleException {
try {
init();
this.started = true;
} catch (Exception e) {
throw new LifecycleException(e);
}
}
public synchronized void stop() throws LifecycleException {
try {
clear();
this.started = false;
} catch (Exception e) {
throw new LifecycleException(e);
}
}
public boolean isStarted() {
return this.started;
}
public String[] getAllFunctionNames() {
Iterator<String> it = this.functionMap.keySet().iterator();
String[] funcNames = new String[this.functionMap.size()];
for (int i = 0; it.hasNext(); i++) {
funcNames[i] = it.next();
}
Arrays.sort(funcNames);
return funcNames;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[FunctionManager] toString()");
Object[] keys = functionMap.keySet().toArray();
for (int i = 0; i < functionMap.size(); i++) {
sb.append("\n " + keys[i] + " : " + functionMap.get(keys[i]));
}
return sb.toString();
}
}
@@ -0,0 +1,65 @@
package com.eactive.eai.transformer.function;
import java.io.Serializable;
public class ParameterDefinition implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String functionName;
private String description;
private int typeId;
private int seqNo;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFunctionName() {
return functionName;
}
public void setFunctionName(String functionName) {
this.functionName = functionName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getTypeId() {
return typeId;
}
public void setTypeId(int typeId) {
this.typeId = typeId;
}
public int getSeqNo() {
return seqNo;
}
public void setSeqNo(int seqNo) {
this.seqNo = seqNo;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ParameterDefinition[ name=").append(name);
sb.append(", functionName=").append(functionName);
sb.append(", description=").append(description);
sb.append(", typeId=").append(typeId);
sb.append(", seqNo=").append(seqNo);
sb.append(" ]");
return sb.toString();
}
}
@@ -0,0 +1,97 @@
package com.eactive.eai.transformer.function.convert;
import java.math.BigDecimal;
import java.util.Stack;
import org.apache.commons.lang3.StringUtils;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
/**
* 소수점이 없는걸 있게 변환하는 함수.
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class ADDPOINT extends PostfixMathCommand {
public ADDPOINT() {
numberOfParameters = 3;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object p3 = inStack.pop();
if (p3 instanceof Number) {
int _p3 = ((Number) p3).intValue();
Object p2 = inStack.pop();
if (p2 instanceof Number) {
int _p2 = ((Number) p2).intValue();
Object p1 = inStack.pop();
if (p1 instanceof String) {
String str1 = (String) p1;
if ( str1.getBytes().length != _p2 + _p3) {
throw new ParseException("Invalid length");
}
inStack.push(addPoint(str1,_p2,_p3));
} else if (p1 instanceof byte[]) {
byte[] bytes = (byte[]) p1;
if ( bytes.length != _p2 + _p3) {
throw new ParseException("Invalid length");
}
inStack.push(addPoint(new String(bytes),_p2,_p3));
} else {
throw new ParseException("Invalid parameter type, p1 is not string/bytes");
}
} else {
throw new ParseException("Invalid parameter type, p2 is not number");
}
} else {
throw new ParseException("Invalid parameter type, p3 is not number");
}
}
public byte[] addPoint(String str , int plus , int minus) throws ParseException {
if (str == null || str.trim().length() ==0 ){
return "0".getBytes();
}
else {
str = str.trim();
}
if(str.length() > (plus+minus) ) {
throw new ParseException("data size overflow > "+(plus+minus) +", data="+ str);
}
//추가로직 juns 20211022
if (minus==0) {
if (str.getBytes().length == plus){
return str.getBytes();
}else{
return StringUtils.leftPad(str, plus).getBytes();
}
}
byte[] result = new byte[plus + minus + 1];
System.arraycopy(str.getBytes(), 0, result, 0, plus);
System.arraycopy(".".getBytes(), 0, result, plus, 1);
System.arraycopy(str.getBytes(), plus, result, plus + 1, minus);
return result;
}
public static void main(String[] args) throws Exception{
ADDPOINT point = new ADDPOINT();
System.out.println(new String(point.addPoint("000000000100",12,0)));
try{
System.out.println(Long.valueOf(new String(point.addPoint("000000000100",12,0))));
}catch(Exception e){
e.printStackTrace();
}
try{
System.out.println(new BigDecimal(new String(point.addPoint("000000000100",12,0))));
}catch(Exception e){
e.printStackTrace();
}
}
}
@@ -0,0 +1,53 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.util.IConv;
/**
* ASCII 값을 EBCDIC으로 변환하는 함수.
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class ASCII2EBCDIC extends PostfixMathCommand {
public ASCII2EBCDIC() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
inStack.push(new byte[0]);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
try {
inStack.push(IConv.asciiToEBCDIC(new String(value)));
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,71 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.function.util.CodeConversion;
/**
* ASCII 값을 EBCDIC으로 변환하는 함수.
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class ASCII2EBCDIC9 extends PostfixMathCommand {
public ASCII2EBCDIC9() {
numberOfParameters = 2;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param2 = inStack.pop();
int len = ((Number) param2).intValue();
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
// inStack.push(null);
// return;
value = new byte[0];
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
try {
byte[] buff = null;
if(value.length > 0) {
buff = CodeConversion.ascToSE9(value, len);
}
else {
buff = CodeConversion.appendHostZero(value, len);
}
// if(len!=buff.length) {
// System.out.println("########################"+value+"=>"+new String(buff));
// }
inStack.push(buff);
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,70 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.function.util.CodeConversion;
/**
* ASCII 값을 EBCDIC으로 변환하는 함수.
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class ASCII2EBCDICM extends PostfixMathCommand {
public ASCII2EBCDICM() {
numberOfParameters = 2;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param2 = inStack.pop();
int len = ((Number) param2).intValue();
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
// inStack.push(null);
// return;
value = new byte[0];
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
try {
value = CodeConversion.simpleToSeal(value);
byte[] buff = null;
if(value.length > 0) {
buff = CodeConversion.ascToSE(value, len);
}
else {
buff = CodeConversion.appendHostSpace(value, len);
}
// if(len!=buff.length)
// System.out.println("######################## ["+new String(value)+"] => ["+new String(buff)+"]");
inStack.push(buff);
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,50 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.util.IConv;
/**
* 전각 ASCII 값을 SO-SI없는 EBCDIC(Graphic)으로 변환하는 함수.
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class ASCII2EBCDICNOSOSI extends PostfixMathCommand {
public ASCII2EBCDICNOSOSI() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
try {
byte[] result = IConv.asciiToEBCDIC(new String(value));
if( result.length == (value.length+2) ) {
byte[] result_nososi = new byte[value.length];
System.arraycopy(result, 1, result_nososi, 0, result_nososi.length);
inStack.push(result_nososi);
}
else {
throw new Exception("Invalid source data, not Seal["+new String(value)+"]");
}
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,69 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.util.IConv;
/**
* 전각 ASCII 값을 SO-SI없는 EBCDIC(Graphic)으로 변환하는 함수.
* 입력 값은 byte[], 결과는 byte[]임.
* 2009.08.12 강길수 차장 요청
* CDS업무을 위한 함수로 ASCII전체가 Space(0x20)인 경우 0x40으로 변환
*/
public class ASCII2EBCDICNOSOSICDS extends PostfixMathCommand {
public ASCII2EBCDICNOSOSICDS() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
try {
boolean isSpaceAll = true;
for(int i=0; i<value.length; i++) {
if(value[i] != (byte)0x20) {
isSpaceAll = false;
break;
}
}
byte[] result = IConv.asciiToEBCDIC(new String(value));
if(isSpaceAll) {
inStack.push(result);
}
else {
if( result.length == (value.length+2) ) {
byte[] result_nososi = new byte[value.length];
System.arraycopy(result, 1, result_nososi, 0, result_nososi.length);
inStack.push(result_nososi);
}
else {
throw new Exception("Invalid source data, not Seal["+new String(value)+"]");
}
}
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,70 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.function.util.CodeConversion;
import com.eactive.eai.transformer.util.IConv;
/**
* ASCII 값을 EBCDIC으로 변환하는 함수.
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class ASCII2EBCDICNOSOSIX extends PostfixMathCommand {
public ASCII2EBCDICNOSOSIX() {
numberOfParameters = 2;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param2 = inStack.pop();
int len = ((Number) param2).intValue();
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
// inStack.push(null);
// return;
value = new byte[0];
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
try {
byte[] buff = null;
if(value.length > 0) {
buff = CodeConversion.appendHostSpace(IConv.asciiToEBCDICNoSOSI( new String(value) ), len);
}
else {
buff = CodeConversion.appendHostSpace(value, len);
}
// if(len!=buff.length) {
// System.out.println("########################"+value+"=>"+new String(buff));
// }
inStack.push(buff);
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,69 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.function.util.CodeConversion;
/**
* ASCII 값을 EBCDIC으로 변환하는 함수.
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class ASCII2EBCDICX extends PostfixMathCommand {
public ASCII2EBCDICX() {
numberOfParameters = 2;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param2 = inStack.pop();
int len = ((Number) param2).intValue();
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
// inStack.push(null);
// return;
value = new byte[0];
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
try {
byte[] buff = null;
if(value.length > 0) {
buff = CodeConversion.ascToSE(value, len);
}
else {
buff = CodeConversion.appendHostSpace(value, len);
}
// if(len!=buff.length) {
// System.out.println("########################"+value+"=>"+new String(buff));
// }
inStack.push(buff);
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,55 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.util.IConv;
/**
* ASCII 값을 EBCDIC HEXA 값으로 변환하는 함수.
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class ASCIIH2EBCDICH extends PostfixMathCommand {
public ASCIIH2EBCDICH() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
// inStack.push(null);
// return;
inStack.push(new byte[0]);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[]가 아닙니다. : " + param);
}
try {
inStack.push(IConv.asciiHexaToEBCDICHexa(value));
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,53 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.util.IConv;
/**
* EBCDIC 값을 ASCII으로 변환하는 함수
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class EBCDIC2ASCII extends PostfixMathCommand {
public EBCDIC2ASCII() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
try {
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
// inStack.push(null);
// return;
inStack.push(new byte[0]);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
inStack.push(IConv.ebcdicToASCII(value).getBytes());
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,53 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.util.IConv;
/**
* EBCDIC 값을 ASCII 확장으로 변환하는 함수
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class EBCDIC2ASCIIEX extends PostfixMathCommand {
public EBCDIC2ASCIIEX() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
try {
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
// inStack.push(null);
// return;
inStack.push(new byte[0]);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
inStack.push(IConv.ebcdicToASCIIEX(value).getBytes());
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,54 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.function.util.CodeConversion;
/**
* EBCDIC 값을 ASCII으로 변환하는 함수
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class EBCDIC2ASCIIM extends PostfixMathCommand {
public EBCDIC2ASCIIM() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
try {
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
// inStack.push(null);
// return;
inStack.push(new byte[0]);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
value = CodeConversion.seToAsc(value);
inStack.push(CodeConversion.sealToSimple(value));
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,55 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.function.util.CodeConversion;
import com.eactive.eai.transformer.util.IConv;
/**
* EBCDIC 값을 ASCII으로 변환하는 함수
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class EBCDIC2ASCIIMEX extends PostfixMathCommand {
public EBCDIC2ASCIIMEX() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
try {
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
// inStack.push(null);
// return;
inStack.push(new byte[0]);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
value = IConv.ebcdicToASCIIEX(value).getBytes();
inStack.push(CodeConversion.sealToSimple(value));
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,44 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.util.IConv;
/**
* SO-SI없는 EBCDIC(Graphic) 값을 전각 ASCII으로 변환하는 함수
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class EBCDIC2ASCIINOSOSI extends PostfixMathCommand {
public EBCDIC2ASCIINOSOSI() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
try {
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
byte[] ebcdic = new byte[value.length + 2];
System.arraycopy(value, 0, ebcdic, 1, value.length);
ebcdic[0] = (byte)0x0E;
ebcdic[ebcdic.length-1] = (byte)0x0F;
inStack.push( IConv.ebcdicToASCII(ebcdic) );
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,61 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.util.IConv;
/**
* SO-SI없는 EBCDIC(Graphic) 값을 전각 ASCII으로 변환하는 함수
* 입력 값은 byte[], 결과는 byte[]임.
* 2009.08.12 강길수 차장 요청
* CDS업무을 위한 함수로 EBCDIC전체가 Space(0x40)인 경우 0x20으로 변환
*/
public class EBCDIC2ASCIINOSOSICDS extends PostfixMathCommand {
public EBCDIC2ASCIINOSOSICDS() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
try {
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
boolean isSpaceAll = true;
for(int i=0; i<value.length; i++) {
if(value[i] != (byte)0x40) {
isSpaceAll = false;
break;
}
}
if(isSpaceAll) {
inStack.push( IConv.ebcdicToASCII(value) );
}
else {
byte[] ebcdic = new byte[value.length + 2];
System.arraycopy(value, 0, ebcdic, 1, value.length);
ebcdic[0] = (byte)0x0E;
ebcdic[ebcdic.length-1] = (byte)0x0F;
inStack.push( IConv.ebcdicToASCII(ebcdic) );
}
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,61 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.util.IConv;
/**
* SO-SI없는 EBCDIC(Graphic) 값을 전각 ASCII으로 변환하는 함수
* 입력 값은 byte[], 결과는 byte[]임.
* 2009.08.12 강길수 차장 요청
* CDS업무을 위한 함수로 EBCDIC전체가 Space(0x40)인 경우 0x20으로 변환
*/
public class EBCDIC2ASCIINOSOSICDSEX extends PostfixMathCommand {
public EBCDIC2ASCIINOSOSICDSEX() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
try {
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
boolean isSpaceAll = true;
for(int i=0; i<value.length; i++) {
if(value[i] != (byte)0x40) {
isSpaceAll = false;
break;
}
}
if(isSpaceAll) {
inStack.push( IConv.ebcdicToASCII(value) );
}
else {
byte[] ebcdic = new byte[value.length + 2];
System.arraycopy(value, 0, ebcdic, 1, value.length);
ebcdic[0] = (byte)0x0E;
ebcdic[ebcdic.length-1] = (byte)0x0F;
inStack.push( IConv.ebcdicToASCIIEX(ebcdic) );
}
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,44 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.util.IConv;
/**
* SO-SI없는 EBCDIC(Graphic) 값을 전각 ASCII으로 변환하는 함수
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class EBCDIC2ASCIINOSOSIEX extends PostfixMathCommand {
public EBCDIC2ASCIINOSOSIEX() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
try {
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
byte[] ebcdic = new byte[value.length + 2];
System.arraycopy(value, 0, ebcdic, 1, value.length);
ebcdic[0] = (byte)0x0E;
ebcdic[ebcdic.length-1] = (byte)0x0F;
inStack.push( IConv.ebcdicToASCIIEX(ebcdic) );
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,44 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.util.IConv;
/**
* SO-SI없는 EBCDIC(Graphic) 값을 전각 ASCII으로 변환하는 함수
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class EBCDIC2ASCIINOSOSISPACEPAD extends PostfixMathCommand {
public EBCDIC2ASCIINOSOSISPACEPAD() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
try {
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
byte[] ebcdic = new byte[value.length + 2];
System.arraycopy(value, 0, ebcdic, 1, value.length);
ebcdic[0] = (byte)0x0E;
ebcdic[ebcdic.length-1] = (byte)0x0F;
inStack.push( IConv.ebcdicToASCIISingleSpace(ebcdic) );
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,44 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.util.IConv;
/**
* SO-SI없는 EBCDIC(Graphic) 값을 전각 ASCII으로 변환하는 함수
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class EBCDIC2ASCIINOSOSISPACEPADEX extends PostfixMathCommand {
public EBCDIC2ASCIINOSOSISPACEPADEX() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
try {
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
byte[] ebcdic = new byte[value.length + 2];
System.arraycopy(value, 0, ebcdic, 1, value.length);
ebcdic[0] = (byte)0x0E;
ebcdic[ebcdic.length-1] = (byte)0x0F;
inStack.push( IConv.ebcdicToASCIISingleSpaceEX(ebcdic) );
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,56 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.function.util.CodeConversion;
import com.eactive.eai.transformer.util.IConv;
/**
* EBCDIC 값을 ASCII 전각으로 변환하는 함수
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class EBCDIC2ASCIIS extends PostfixMathCommand {
public EBCDIC2ASCIIS() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
try {
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
// inStack.push(null);
// return;
inStack.push(new byte[0]);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
String simple = IConv.ebcdicToASCII(value);
String seal = CodeConversion.simpleToSeal(simple);
inStack.push(seal.getBytes());
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,68 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.util.IConv;
/**
* EBCDIC 값을 ASCII으로 변환하는 함수
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class EBCDIC2ASCIISS extends PostfixMathCommand {
public EBCDIC2ASCIISS() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
try {
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
// inStack.push(null);
// return;
inStack.push(new byte[0]);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
// 2009.12.02 강길수 차장 요청
// 첫바이트가 EBCDIC 4(0xF4)이면 SI에 Space 2자를 패딩하도록 변환
// 첫 바이트는 데이터에서 제외된다.
// ASCII 기본형
byte flag = value[0];
byte[] cutBytes = new byte[value.length -1];
System.arraycopy(value, 1, cutBytes, 0, cutBytes.length);
if(flag == (byte)0xF4) {
inStack.push(IConv.ebcdicToASCIISIDoubleSpace(cutBytes).getBytes());
}
else {
inStack.push(IConv.ebcdicToASCII(cutBytes).getBytes());
}
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,68 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.util.IConv;
/**
* EBCDIC 값을 ASCII으로 변환하는 함수
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class EBCDIC2ASCIISSEX extends PostfixMathCommand {
public EBCDIC2ASCIISSEX() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
try {
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
// inStack.push(null);
// return;
inStack.push(new byte[0]);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
// 2009.12.02 강길수 차장 요청
// 첫바이트가 EBCDIC 4(0xF4)이면 SI에 Space 2자를 패딩하도록 변환
// 첫 바이트는 데이터에서 제외된다.
// ASCII 확장형
byte flag = value[0];
byte[] cutBytes = new byte[value.length -1];
System.arraycopy(value, 1, cutBytes, 0, cutBytes.length);
if(flag == (byte)0xF4) {
inStack.push(IConv.ebcdicToASCIISIDoubleSpaceEX(cutBytes).getBytes());
}
else {
inStack.push(IConv.ebcdicToASCIIEX(cutBytes).getBytes());
}
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,53 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.util.IConv;
/**
* EBCDIC 값을 ASCII으로 변환하는 함수
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class EBCDIC2ASCIIWITHSOSI extends PostfixMathCommand {
public EBCDIC2ASCIIWITHSOSI() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
try {
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
// inStack.push(null);
// return;
inStack.push(new byte[0]);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
inStack.push(IConv.ebcdicToASCIIWithSOSI(value).getBytes());
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,53 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.util.IConv;
/**
* EBCDIC 값을 ASCII으로 변환하는 함수
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class EBCDIC2ASCIIWITHSOSIEX extends PostfixMathCommand {
public EBCDIC2ASCIIWITHSOSIEX() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
try {
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
// inStack.push(null);
// return;
inStack.push(new byte[0]);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
inStack.push(IConv.ebcdicToASCIIWithSOSIEX(value).getBytes());
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,51 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.util.IConv;
/**
* EBCDIC 값을 ASCII HEXA 값으로 변환하는 함수
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class EBCDICH2ASCIIH extends PostfixMathCommand {
public EBCDICH2ASCIIH() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
try {
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
inStack.push(new byte[0]);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[]가 아닙니다. : " + param);
}
inStack.push(IConv.ebcdicHexaToASCIIHexa(value));
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,34 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
/**
* 길이만큼 Space(0x40)으로 패딩하는 함수.
* 입력 값은 int, 결과는 byte[]임.
*/
public class EBCDICSPACEPAD extends PostfixMathCommand {
public EBCDICSPACEPAD() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
try {
int len = ((Number) param).intValue();
byte[] value = new byte[len];
for(int i=0; i<len; i++) {
value[i] = (byte)0x40;
}
inStack.push(value);
} catch (Exception e) {
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,34 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
/**
* 길이만큼 Space(0x40)으로 패딩하는 함수.
* 입력 값은 int, 결과는 byte[]임.
*/
public class EBCDICZEROPAD extends PostfixMathCommand {
public EBCDICZEROPAD() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
try {
int len = ((Number) param).intValue();
byte[] value = new byte[len];
for(int i=0; i<len; i++) {
value[i] = (byte)0xF0;
}
inStack.push(value);
} catch (Exception e) {
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,66 @@
package com.eactive.eai.transformer.function.convert;
import java.io.UnsupportedEncodingException;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
/**
* EUC-KR 값을 UTF-8 로 변환하는 함수.
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class EUCKR2UTF8 extends PostfixMathCommand {
public EUCKR2UTF8() {
numberOfParameters = 1;
}
private String sourceChar = "EUC-KR";
private String targetChar = "UTF-8";
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
try {
value = ((String) param).getBytes(sourceChar);
} catch (UnsupportedEncodingException e) {
throw new ParseException(sourceChar+" conversion 오류 : " + e.getMessage());
}
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
try{
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes(sourceChar);
} else {
value =((Number) param).toString().getBytes(sourceChar);
}
} catch (UnsupportedEncodingException e) {
throw new ParseException(sourceChar+" conversion 오류 : " + e.getMessage());
}
} else if (param instanceof Number) {
try{
value = ((Number) param).toString().getBytes(sourceChar);
} catch (UnsupportedEncodingException e) {
throw new ParseException(sourceChar+" conversion 오류 : " + e.getMessage());
}
} else if (param == null) {
inStack.push(new byte[0]);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
try {
inStack.push(new String(value,sourceChar).getBytes(targetChar));
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,45 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
/**
* 0x00값을 Space(0x20)으로 변환하는 함수.
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class Null2Space extends PostfixMathCommand {
public Null2Space() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param == null) {
inStack.push(new byte[0]);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
try {
for(int i=0; i<value.length; i++) {
if(value[i] == (byte)0x00) value[i] = (byte)0x20;
}
inStack.push(value);
} catch (Exception e) {
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,147 @@
package com.eactive.eai.transformer.function.convert;
import java.math.BigDecimal;
import java.util.Stack;
import org.apache.commons.lang3.StringUtils;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
/**
* 소수점이 있는걸 없게 변환하는 함수.
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class REMOVEPOINT extends PostfixMathCommand {
public REMOVEPOINT() {
numberOfParameters = 3;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object p3 = inStack.pop();
if (p3 instanceof Number) {
int _p3 = ((Number) p3).intValue();
Object p2 = inStack.pop();
if (p2 instanceof Number) {
int _p2 = ((Number) p2).intValue();
Object p1 = inStack.pop();
if (p1 instanceof String) {
String str1 = (String) p1;
inStack.push(removePointUnsigned(str1,_p2,_p3));
} else if (p1 instanceof byte[]) {
byte[] bytes = (byte[]) p1;
inStack.push(removePointUnsigned(new String(bytes),_p2,_p3));
} else if (p1 instanceof BigDecimal) {
String str1 = ((BigDecimal) p1).toPlainString();
inStack.push(removePointUnsigned(str1,_p2,_p3));
} else if (p1 instanceof Double) {
// String str1 = ((Double) p1).toString();
String str1 = (BigDecimal.valueOf((Double) p1)).toPlainString();
inStack.push(removePointUnsigned(str1,_p2,_p3));
} else {
throw new ParseException("Invalid parameter type, p1 is not string/bytes/double/number");
}
} else {
throw new ParseException("Invalid parameter type, p2 is not number");
}
} else {
throw new ParseException("Invalid parameter type, p3 is not number");
}
}
public byte[] removePointUnsigned(String str , int plus , int minus) throws ParseException {
boolean isSigned = false;
StringBuilder sb = new StringBuilder(plus+minus);
String nBody = null;
String dBody = null;
if (str == null || str.trim().length() ==0 ){
return StringUtils.leftPad("0",plus+minus,"0").getBytes();
}
else {
str = str.trim();
}
String signBit = str.substring(0,1);
if(signBit.equals("+") || signBit.equals("-")) {
throw new ParseException("sign bit not supported ("+signBit +"), data="+ str);
}
int pointPos = str.indexOf(".");
if (pointPos<0){
if(str.length() > (plus+minus)) {
throw new ParseException("data size overflow integer part >"+(plus+minus) +", data="+ str);
}
}
else {
if(pointPos > plus) {
throw new ParseException("data size overflow integer part > "+plus +", data="+ str);
}
if((str.length() - pointPos - 1) > minus) {
throw new ParseException("data size overflow decimal part > "+minus +", data="+ str);
}
}
if (pointPos<0){
nBody = str;
dBody = "";
}
else {
nBody = str.substring(0,pointPos);
dBody = str.substring(pointPos+1);
}
nBody = StringUtils.leftPad(nBody, plus, "0");
dBody = StringUtils.rightPad(dBody, minus, "0");
if(isSigned) {
sb.append(signBit);
}
sb.append(nBody);
sb.append(dBody);
return sb.toString().getBytes();
}
public static void main(String[] args) throws Exception{
REMOVEPOINT point = new REMOVEPOINT();
// System.out.println(new String(point.addStack(new String("1.2"), 6, 2)));
// System.out.println(new String(point.addStack(new String("1.2"), 6, 0)));
// System.out.println(new String(point.addStack(new String("1.2"), 12, 2)));
// System.out.println(new String(point.addStack(new BigDecimal("1000000000000000000.2"), 20, 2)));
System.out.println(new String(point.addStack(new Double("1000000000000000.2"), 20, 2))); // 16 decimal digits available
System.out.println(new String(point.addStack(new Double("1.0000000000000002"), 1, 20))); // 16 decimal digits available
}
/**
* 내부 테스트용
* @param o
* @param n
* @param f
* @return
*/
protected byte[] addStack(Object o, int n, int f){
Stack inStack = new Stack();
inStack.add(o);
inStack.add(n);
inStack.add(f);
try {
run(inStack);
} catch (ParseException e) {
e.printStackTrace();
return new byte[0];
}
return (byte[])inStack.pop();
}
}
@@ -0,0 +1,152 @@
package com.eactive.eai.transformer.function.convert;
import java.math.BigDecimal;
import java.util.Stack;
import org.apache.commons.lang3.StringUtils;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
/**
* 소수점이 있는걸 없게 변환하는 함수.
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class REMOVEPOINTS extends PostfixMathCommand {
public REMOVEPOINTS() {
numberOfParameters = 3;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object p3 = inStack.pop();
if (p3 instanceof Number) {
int _p3 = ((Number) p3).intValue();
Object p2 = inStack.pop();
if (p2 instanceof Number) {
int _p2 = ((Number) p2).intValue();
Object p1 = inStack.pop();
if (p1 instanceof String) {
String str1 = (String) p1;
inStack.push(removePointSigned(str1,_p2,_p3));
} else if (p1 instanceof byte[]) {
byte[] bytes = (byte[]) p1;
inStack.push(removePointSigned(new String(bytes),_p2,_p3));
} else if (p1 instanceof BigDecimal) {
String str1 = ((BigDecimal) p1).toPlainString();
inStack.push(removePointSigned(str1,_p2,_p3));
} else if (p1 instanceof Number) {
String str1 = ((Number) p1).toString();
inStack.push(removePointSigned(str1,_p2,_p3));
} else {
throw new ParseException("Invalid parameter type, p1 is not string/bytes/double/number");
}
} else {
throw new ParseException("Invalid parameter type, p2 is not number");
}
} else {
throw new ParseException("Invalid parameter type, p3 is not number");
}
}
public byte[] removePointSigned(String str , int plus , int minus) throws ParseException {
boolean isSigned = false;
StringBuilder sb = new StringBuilder(plus+minus);
String nBody = null;
String dBody = null;
if (str == null || str.trim().length() ==0 ){
return StringUtils.leftPad("0",plus+minus,"0").getBytes();
}
else {
str = str.trim();
}
String signBit = str.substring(0,1);
if(signBit.equals("+") || signBit.equals("-")) {
isSigned = true;
str = str.substring(1);
}
else {
isSigned = false;
signBit = "+";
}
// 부호도 길이에 포함됨
plus = plus -1;
int pointPos = str.indexOf(".");
if (pointPos<0){
if(str.length() > plus) {
throw new ParseException("data size overflow integer part >"+plus+", data="+ str);
}
}
else {
if(pointPos > plus) {
throw new ParseException("data size overflow integer part > "+plus +", data="+ str);
}
if((str.length() - pointPos - 1) > minus) {
// System.out.println(str.length());
// System.out.println(pointPos);
throw new ParseException("data size overflow decimal part > "+minus +", data="+ str);
}
}
if (pointPos<0){
nBody = str;
dBody = "";
}
else {
nBody = str.substring(0,pointPos);
dBody = str.substring(pointPos+1);
}
nBody = StringUtils.leftPad(nBody, plus, "0");
dBody = StringUtils.rightPad(dBody, minus, "0");
sb.append(signBit);
sb.append(nBody);
sb.append(dBody);
return sb.toString().getBytes();
}
public static void main(String[] args) throws Exception{
REMOVEPOINTS point = new REMOVEPOINTS();
System.out.println(new String(point.addStack(new String("-1.2"), 6, 2)));
System.out.println(new String(point.addStack(new String("-1.2"), 6, 0)));
System.out.println(new String(point.addStack(new String("-1.2"), 12, 2)));
System.out.println(new String(point.addStack(new BigDecimal("-1000000000000000000.2"), 20, 2)));
System.out.println(new String(point.addStack(new Double("-1000000000000000000.2"), 20, 2)));
}
/**
* 내부 테스트용
* @param o
* @param n
* @param f
* @return
*/
protected byte[] addStack(Object o, int n, int f){
Stack inStack = new Stack();
inStack.add(o);
inStack.add(n);
inStack.add(f);
try {
run(inStack);
} catch (ParseException e) {
e.printStackTrace();
return new byte[0];
}
return (byte[])inStack.pop();
}
}
@@ -0,0 +1,45 @@
package com.eactive.eai.transformer.function.convert;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
/**
* 0x20값을 Space(0x30)으로 변환하는 함수.
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class Space2Zero extends PostfixMathCommand {
public Space2Zero() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param == null) {
inStack.push(new byte[0]);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
try {
for(int i=0; i<value.length; i++) {
if(value[i] == (byte)0x20) value[i] = (byte)0x30;
}
inStack.push(value);
} catch (Exception e) {
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,65 @@
package com.eactive.eai.transformer.function.convert;
import java.io.UnsupportedEncodingException;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
/**
* UTF-8 값을 EUC-KR 로 변환하는 함수.
* 입력 값은 byte[], 결과는 byte[]임.
*/
public class UTF82EUCKR extends PostfixMathCommand {
public UTF82EUCKR() {
numberOfParameters = 1;
}
private String sourceChar = "UTF-8";
private String targetChar = "EUC-KR";
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
try {
value = ((String) param).getBytes(sourceChar);
} catch (UnsupportedEncodingException e) {
throw new ParseException(sourceChar+" conversion 오류 : " + e.getMessage());
}
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
try{
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes(sourceChar);
} else {
value =((Number) param).toString().getBytes(sourceChar);
}
} catch (UnsupportedEncodingException e) {
throw new ParseException(sourceChar+" conversion 오류 : " + e.getMessage());
}
} else if (param instanceof Number) {
try{
value = ((Number) param).toString().getBytes(sourceChar);
} catch (UnsupportedEncodingException e) {
throw new ParseException(sourceChar+" conversion 오류 : " + e.getMessage());
}
} else if (param == null) {
inStack.push(new byte[0]);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
try {
inStack.push(new String(value,sourceChar).getBytes(targetChar));
} catch (Exception e) {
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,49 @@
package com.eactive.eai.transformer.function.crypto;
import java.util.Stack;
import org.apache.commons.codec.binary.Base64;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
public class Base64Decode extends PostfixMathCommand {
public Base64Decode() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
inStack.push(null);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[] 또는 String이 아닙니다. : " + param);
}
try {
Base64 base = new Base64();
value = base.decode(value);
inStack.push(value);
} catch (Exception e) {
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,49 @@
package com.eactive.eai.transformer.function.crypto;
import java.util.Stack;
import org.apache.commons.codec.binary.Base64;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
public class Base64Encode extends PostfixMathCommand {
public Base64Encode() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
inStack.push(null);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[] 또는 String이 아닙니다. : " + param);
}
try {
Base64 base = new Base64();
value = base.encode(value);
inStack.push(value);
} catch (Exception e) {
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,93 @@
package com.eactive.eai.transformer.function.crypto;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
public class Decrypt extends PostfixMathCommand {
public Decrypt() {
numberOfParameters = 3;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object text = inStack.pop();
Object bus = inStack.pop();
Object algo = inStack.pop();
/**
* check algorithm
*/
if (!(algo instanceof String)) {
throw new ParseException("1st parameter (algorithm) must be String data type");
} else if (!((String) algo).matches("(des|DES|des3|DES3|seed|SEED)")) {
throw new ParseException("1st parameter (algorithm) must be one of (DES|DES3|SEED)");
}
/**
* check business
*/
if (!(bus instanceof String))
throw new ParseException("2nd parameter (algorithm) must be String data type");
/**
* convert text to byte[]
*/
byte[] value = convertToBytes(text);
if (value == null) {
inStack.push(null);
return;
}
/**
* encrypt
*/
try {
if (((String) algo).matches("(des|DES)")) {
byte[] keyData = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
inStack.push(new DesCodec(keyData).decrypt(value));
} else if (((String) algo).matches("(des3|DES3)")) {
byte[] keyData = {
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01
};
inStack.push(new Des3Codec(keyData).decrypt(value));
} else if (((String) algo).matches("(seed|SEED)")) {
inStack.push(new SeedCodec().decrypt(value));
} else {
throw new ParseException("1st parameter (algorithm) must be one of (DES|DES3|SEED)");
}
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
private byte[] convertToBytes(Object text) throws ParseException {
byte[] value = null;
if (text instanceof String) {
value = ((String) text).getBytes();
} else if (text instanceof byte[]) {
value = (byte[]) text;
} else if (text instanceof Double) {
if (((Double) text).doubleValue() == Math.round(((Double) text).doubleValue())) {
value = new Long(Math.round(((Double) text).doubleValue())).toString().getBytes();
} else {
value =((Number) text).toString().getBytes();
}
} else if (text instanceof Number) {
value = ((Number) text).toString().getBytes();
} else if (text == null) {
value = null;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[] 또는 String이 아닙니다. : " + text);
}
return value;
}
}
@@ -0,0 +1,79 @@
package com.eactive.eai.transformer.function.crypto;
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
public class Des3Codec {
Cipher ecipher;
Cipher dcipher;
public Des3Codec(byte[] keyData) throws GeneralSecurityException {
try {
//SecretKey key = KeyGenerator.getInstance("DES").generateKey();
DESedeKeySpec des3KeySpec = new DESedeKeySpec(keyData);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey key = keyFactory.generateSecret(des3KeySpec);
/* Initialization Vector of 8 bytes set to zero. */
IvParameterSpec iv = new IvParameterSpec(new byte[8]);
ecipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
dcipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
ecipher.init(Cipher.ENCRYPT_MODE, key, iv);
dcipher.init(Cipher.DECRYPT_MODE, key, iv);
} catch (javax.crypto.NoSuchPaddingException e) {
throw e;
} catch (java.security.NoSuchAlgorithmException e) {
throw e;
} catch (java.security.InvalidKeyException e) {
throw e;
} catch (java.security.InvalidAlgorithmParameterException e) {
throw e;
}
}
public byte[] encrypt(byte[] utf8) throws Exception {
try {
// Encode the string into bytes using utf-8
//byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
//return new sun.misc.BASE64Encoder().encode(enc);
return enc;
} catch (javax.crypto.BadPaddingException e) {
throw e;
} catch (IllegalBlockSizeException e) {
throw e;
}
}
public byte[] decrypt(byte[] dec) throws Exception {
try {
// Decode base64 to get bytes
//byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
//return new String(utf8, "UTF8");
return utf8;
} catch (javax.crypto.BadPaddingException e) {
throw e;
} catch (IllegalBlockSizeException e) {
throw e;
}
}
}
@@ -0,0 +1,55 @@
package com.eactive.eai.transformer.function.crypto;
import java.util.Base64;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
public class Des3Decrypt extends PostfixMathCommand {
public Des3Decrypt() {
numberOfParameters = -1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
inStack.push(null);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[] 또는 String이 아닙니다. : " + param);
}
try {
byte[] keyData = {
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01
};
byte[] decByte = Base64.getDecoder().decode(value);
inStack.push(new Des3Codec(keyData).decrypt(decByte));
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,55 @@
package com.eactive.eai.transformer.function.crypto;
import java.util.Base64;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
public class Des3Encrypt extends PostfixMathCommand {
public Des3Encrypt() {
numberOfParameters = -1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
inStack.push(null);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[] 또는 String이 아닙니다. : " + param);
}
try {
byte[] keyData = {
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01
};
byte[] encByte = new Des3Codec(keyData).encrypt(value);
inStack.push(Base64.getEncoder().encode(encByte));
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,73 @@
package com.eactive.eai.transformer.function.crypto;
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public class DesCodec {
Cipher ecipher;
Cipher dcipher;
public DesCodec(byte[] keyData) throws GeneralSecurityException {
try {
//SecretKey key = KeyGenerator.getInstance("DES").generateKey();
DESKeySpec desKeySpec = new DESKeySpec(keyData);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(desKeySpec);
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
} catch (javax.crypto.NoSuchPaddingException e) {
throw e;
} catch (java.security.NoSuchAlgorithmException e) {
throw e;
} catch (java.security.InvalidKeyException e) {
throw e;
}
}
public byte[] encrypt(byte[] utf8) throws Exception {
try {
// Encode the string into bytes using utf-8
//byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
//return new sun.misc.BASE64Encoder().encode(enc);
return enc;
} catch (javax.crypto.BadPaddingException e) {
throw e;
} catch (IllegalBlockSizeException e) {
throw e;
}
}
public byte[] decrypt(byte[] dec) throws Exception {
try {
// Decode base64 to get bytes
//byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
//return new String(utf8, "UTF8");
return utf8;
} catch (javax.crypto.BadPaddingException e) {
throw e;
} catch (IllegalBlockSizeException e) {
throw e;
}
}
}
@@ -0,0 +1,50 @@
package com.eactive.eai.transformer.function.crypto;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
public class DesDecrypt extends PostfixMathCommand {
public DesDecrypt() {
numberOfParameters = -1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
inStack.push(null);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[] 또는 String이 아닙니다. : " + param);
}
try {
byte[] keyData = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
//SecretKey key = KeyGenerator.getInstance("DES").generateKey();
inStack.push(new DesCodec(keyData).decrypt(value));
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,48 @@
package com.eactive.eai.transformer.function.crypto;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
public class DesEncrypt extends PostfixMathCommand {
public DesEncrypt() {
numberOfParameters = -1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
inStack.push(null);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[] 또는 String이 아닙니다. : " + param);
}
try {
byte[] keyData = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
inStack.push(new DesCodec(keyData).encrypt(value));
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,93 @@
package com.eactive.eai.transformer.function.crypto;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
public class Encrypt extends PostfixMathCommand {
public Encrypt() {
numberOfParameters = 3;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object text = inStack.pop();
Object bus = inStack.pop();
Object algo = inStack.pop();
/**
* check algorithm
*/
if (!(algo instanceof String)) {
throw new ParseException("1st parameter (algorithm) must be String data type");
} else if (!((String) algo).matches("(des|DES|des3|DES3|seed|SEED)")) {
throw new ParseException("1st parameter (algorithm) must be one of (DES|DES3|SEED)");
}
/**
* check business
*/
if (!(bus instanceof String))
throw new ParseException("2nd parameter (algorithm) must be String data type");
/**
* convert text to byte[]
*/
byte[] value = convertToBytes(text);
if (value == null) {
inStack.push(null);
return;
}
/**
* encrypt
*/
try {
if (((String) algo).matches("(des|DES)")) {
byte[] keyData = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
inStack.push(new DesCodec(keyData).encrypt(value));
} else if (((String) algo).matches("(des3|DES3)")) {
byte[] keyData = {
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01
};
inStack.push(new Des3Codec(keyData).encrypt(value));
} else if (((String) algo).matches("(seed|SEED)")) {
inStack.push(new SeedCodec().encrypt(value));
} else {
throw new ParseException("1st parameter (algorithm) must be one of (DES|DES3|SEED)");
}
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
private byte[] convertToBytes(Object text) throws ParseException {
byte[] value = null;
if (text instanceof String) {
value = ((String) text).getBytes();
} else if (text instanceof byte[]) {
value = (byte[]) text;
} else if (text instanceof Double) {
if (((Double) text).doubleValue() == Math.round(((Double) text).doubleValue())) {
value = new Long(Math.round(((Double) text).doubleValue())).toString().getBytes();
} else {
value =((Number) text).toString().getBytes();
}
} else if (text instanceof Number) {
value = ((Number) text).toString().getBytes();
} else if (text == null) {
value = null;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[] 또는 String이 아닙니다. : " + text);
}
return value;
}
}
@@ -0,0 +1,53 @@
package com.eactive.eai.transformer.function.crypto;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.penta.scphost.ScpHostEcod;
public class SCPDecode extends PostfixMathCommand {
public SCPDecode() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
inStack.push(new byte[0]);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
try {
ScpHostEcod enc = new ScpHostEcod();
byte[] res = enc.ScpDecode(value, 0); // ASCII Decode
inStack.push(res);
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,53 @@
package com.eactive.eai.transformer.function.crypto;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.penta.scphost.ScpHostEcod;
public class SCPEncode extends PostfixMathCommand {
public SCPEncode() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
inStack.push(new byte[0]);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
try {
ScpHostEcod enc = new ScpHostEcod();
byte[] res = enc.ScpEncode(value, 0); // ASCII Encode
inStack.push(res);
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,79 @@
package com.eactive.eai.transformer.function.crypto;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
public class SamsungPayNSHCDecode extends PostfixMathCommand {
public SamsungPayNSHCDecode() {
numberOfParameters = 2;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
//NSHC 복호화 컬럼은 param2 로 받고, 그에 대한 키값(RSA복호화)을 param1로 받음 (stack이라 순서 반대)
//key value
Object param1 = inStack.pop();
//Data
Object param2 = inStack.pop();
byte[] value = null;
byte[] key = null;
if (param2 instanceof String) {
value = ((String) param2).getBytes();
} else if (param2 instanceof byte[]) {
value = (byte[]) param2;
} else if (param2 instanceof Double) {
if (((Double) param2).doubleValue() == Math.round(((Double) param2).doubleValue())) {
value = new Long(Math.round(((Double) param2).doubleValue())).toString().getBytes();
} else {
value =((Number) param2).toString().getBytes();
}
} else if (param2 instanceof Number) {
value = ((Number) param2).toString().getBytes();
} else if (param2 == null) {
inStack.push(new byte[0]);
// System.out.println("NSHC : Data is NULL");
return;
} else {
throw new ParseException("Data 값이 byte[], String이 아닙니다. : " + param2);
}
if (param1 instanceof String) {
key = ((String) param1).getBytes();
} else if (param1 instanceof byte[]) {
key = (byte[]) param1;
} else if (param1 instanceof Double) {
if (((Double) param1).doubleValue() == Math.round(((Double) param1).doubleValue())) {
key = new Long(Math.round(((Double) param1).doubleValue())).toString().getBytes();
} else {
key =((Number) param1).toString().getBytes();
}
} else if (param1 instanceof Number) {
key = ((Number) param1).toString().getBytes();
} else if (param1 == null) {
inStack.push(new byte[0]);
// System.out.println("NSHC : Key value is NULL");
return;
} else {
throw new ParseException("Key 값이 byte[], String이 아닙니다. : " + param1);
}
// param2의 복호화 키값을 파라메터로 하여 param1 NSHC복호화
try {
// NFilter nfilter = new NFilter();
// byte[] res = nfilter.decNum(new String(key), new String(value)).getBytes();
// inStack.push(res);
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,71 @@
package com.eactive.eai.transformer.function.crypto;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
public class SamsungPayRSADecode extends PostfixMathCommand {
public SamsungPayRSADecode() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
String localKey = "88888888";
String pubKeyFile="/fsapp/eai/MagicPKI/key/public.key"; // 공개키 저장파일명
String priEncKeyFile="/fsapp/eai/MagicPKI/key/private.key"; // 개인키 저장파일명
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
// System.out.println("RSA : Data is NULL");
inStack.push(new byte[0]);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[], String이 아닙니다. : " + param);
}
try {
// DSToolkit.init("/fsapp/eai/MagicPKI/license");
// PrivateKey priKey = null;
// PublicKey pubKey = null;
// pubKey = new PublicKey( Disk.read(pubKeyFile) );
// priKey = Disk.readPriKey( priEncKeyFile, localKey );
//
// Base64 base64 = new Base64();
// byte[] decValue = null;
//
// Cipher rsa = Cipher.getInstance("RSA");
// rsa.init(Cipher.DECRYPT_MODE, priKey);
// decValue = base64.decode(new String(value));
// byte[] res = rsa.doFinal(decValue);
//
// inStack.push(res);
//
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,18 @@
package com.eactive.eai.transformer.function.crypto;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
public class Seed128Decrypt extends PostfixMathCommand {
public Seed128Decrypt() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
}
}
@@ -0,0 +1,18 @@
package com.eactive.eai.transformer.function.crypto;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
public class Seed128Encrypt extends PostfixMathCommand {
public Seed128Encrypt() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
}
}
@@ -0,0 +1,530 @@
package com.eactive.eai.transformer.function.crypto;
/*******************************************************************************
* Made : 2006. 7.18. Update : 2006.11.24 FILE : seedx_test.java
*
* DESCRIPTION: Core routines for the enhanced SEED
*
*******************************************************************************/
public class SeedCodec {
private static int SS0[] = {
0x2989a1a8, 0x05858184, 0x16c6d2d4, 0x13c3d3d0, 0x14445054, 0x1d0d111c, 0x2c8ca0ac, 0x25052124,
0x1d4d515c, 0x03434340, 0x18081018, 0x1e0e121c, 0x11415150, 0x3cccf0fc, 0x0acac2c8, 0x23436360,
0x28082028, 0x04444044, 0x20002020, 0x1d8d919c, 0x20c0e0e0, 0x22c2e2e0, 0x08c8c0c8, 0x17071314,
0x2585a1a4, 0x0f8f838c, 0x03030300, 0x3b4b7378, 0x3b8bb3b8, 0x13031310, 0x12c2d2d0, 0x2ecee2ec,
0x30407070, 0x0c8c808c, 0x3f0f333c, 0x2888a0a8, 0x32023230, 0x1dcdd1dc, 0x36c6f2f4, 0x34447074,
0x2ccce0ec, 0x15859194, 0x0b0b0308, 0x17475354, 0x1c4c505c, 0x1b4b5358, 0x3d8db1bc, 0x01010100,
0x24042024, 0x1c0c101c, 0x33437370, 0x18889098, 0x10001010, 0x0cccc0cc, 0x32c2f2f0, 0x19c9d1d8,
0x2c0c202c, 0x27c7e3e4, 0x32427270, 0x03838380, 0x1b8b9398, 0x11c1d1d0, 0x06868284, 0x09c9c1c8,
0x20406060, 0x10405050, 0x2383a3a0, 0x2bcbe3e8, 0x0d0d010c, 0x3686b2b4, 0x1e8e929c, 0x0f4f434c,
0x3787b3b4, 0x1a4a5258, 0x06c6c2c4, 0x38487078, 0x2686a2a4, 0x12021210, 0x2f8fa3ac, 0x15c5d1d4,
0x21416160, 0x03c3c3c0, 0x3484b0b4, 0x01414140, 0x12425250, 0x3d4d717c, 0x0d8d818c, 0x08080008,
0x1f0f131c, 0x19899198, 0x00000000, 0x19091118, 0x04040004, 0x13435350, 0x37c7f3f4, 0x21c1e1e0,
0x3dcdf1fc, 0x36467274, 0x2f0f232c, 0x27072324, 0x3080b0b0, 0x0b8b8388, 0x0e0e020c, 0x2b8ba3a8,
0x2282a2a0, 0x2e4e626c, 0x13839390, 0x0d4d414c, 0x29496168, 0x3c4c707c, 0x09090108, 0x0a0a0208,
0x3f8fb3bc, 0x2fcfe3ec, 0x33c3f3f0, 0x05c5c1c4, 0x07878384, 0x14041014, 0x3ecef2fc, 0x24446064,
0x1eced2dc, 0x2e0e222c, 0x0b4b4348, 0x1a0a1218, 0x06060204, 0x21012120, 0x2b4b6368, 0x26466264,
0x02020200, 0x35c5f1f4, 0x12829290, 0x0a8a8288, 0x0c0c000c, 0x3383b3b0, 0x3e4e727c, 0x10c0d0d0,
0x3a4a7278, 0x07474344, 0x16869294, 0x25c5e1e4, 0x26062224, 0x00808080, 0x2d8da1ac, 0x1fcfd3dc,
0x2181a1a0, 0x30003030, 0x37073334, 0x2e8ea2ac, 0x36063234, 0x15051114, 0x22022220, 0x38083038,
0x34c4f0f4, 0x2787a3a4, 0x05454144, 0x0c4c404c, 0x01818180, 0x29c9e1e8, 0x04848084, 0x17879394,
0x35053134, 0x0bcbc3c8, 0x0ecec2cc, 0x3c0c303c, 0x31417170, 0x11011110, 0x07c7c3c4, 0x09898188,
0x35457174, 0x3bcbf3f8, 0x1acad2d8, 0x38c8f0f8, 0x14849094, 0x19495158, 0x02828280, 0x04c4c0c4,
0x3fcff3fc, 0x09494148, 0x39093138, 0x27476364, 0x00c0c0c0, 0x0fcfc3cc, 0x17c7d3d4, 0x3888b0b8,
0x0f0f030c, 0x0e8e828c, 0x02424240, 0x23032320, 0x11819190, 0x2c4c606c, 0x1bcbd3d8, 0x2484a0a4,
0x34043034, 0x31c1f1f0, 0x08484048, 0x02c2c2c0, 0x2f4f636c, 0x3d0d313c, 0x2d0d212c, 0x00404040,
0x3e8eb2bc, 0x3e0e323c, 0x3c8cb0bc, 0x01c1c1c0, 0x2a8aa2a8, 0x3a8ab2b8, 0x0e4e424c, 0x15455154,
0x3b0b3338, 0x1cccd0dc, 0x28486068, 0x3f4f737c, 0x1c8c909c, 0x18c8d0d8, 0x0a4a4248, 0x16465254,
0x37477374, 0x2080a0a0, 0x2dcde1ec, 0x06464244, 0x3585b1b4, 0x2b0b2328, 0x25456164, 0x3acaf2f8,
0x23c3e3e0, 0x3989b1b8, 0x3181b1b0, 0x1f8f939c, 0x1e4e525c, 0x39c9f1f8, 0x26c6e2e4, 0x3282b2b0,
0x31013130, 0x2acae2e8, 0x2d4d616c, 0x1f4f535c, 0x24c4e0e4, 0x30c0f0f0, 0x0dcdc1cc, 0x08888088,
0x16061214, 0x3a0a3238, 0x18485058, 0x14c4d0d4, 0x22426260, 0x29092128, 0x07070304, 0x33033330,
0x28c8e0e8, 0x1b0b1318, 0x05050104, 0x39497178, 0x10809090, 0x2a4a6268, 0x2a0a2228, 0x1a8a9298
};
private static int SS1[] = {
0x38380830, 0xe828c8e0, 0x2c2d0d21, 0xa42686a2, 0xcc0fcfc3, 0xdc1eced2, 0xb03383b3, 0xb83888b0,
0xac2f8fa3, 0x60204060, 0x54154551, 0xc407c7c3, 0x44044440, 0x6c2f4f63, 0x682b4b63, 0x581b4b53,
0xc003c3c3, 0x60224262, 0x30330333, 0xb43585b1, 0x28290921, 0xa02080a0, 0xe022c2e2, 0xa42787a3,
0xd013c3d3, 0x90118191, 0x10110111, 0x04060602, 0x1c1c0c10, 0xbc3c8cb0, 0x34360632, 0x480b4b43,
0xec2fcfe3, 0x88088880, 0x6c2c4c60, 0xa82888a0, 0x14170713, 0xc404c4c0, 0x14160612, 0xf434c4f0,
0xc002c2c2, 0x44054541, 0xe021c1e1, 0xd416c6d2, 0x3c3f0f33, 0x3c3d0d31, 0x8c0e8e82, 0x98188890,
0x28280820, 0x4c0e4e42, 0xf436c6f2, 0x3c3e0e32, 0xa42585a1, 0xf839c9f1, 0x0c0d0d01, 0xdc1fcfd3,
0xd818c8d0, 0x282b0b23, 0x64264662, 0x783a4a72, 0x24270723, 0x2c2f0f23, 0xf031c1f1, 0x70324272,
0x40024242, 0xd414c4d0, 0x40014141, 0xc000c0c0, 0x70334373, 0x64274763, 0xac2c8ca0, 0x880b8b83,
0xf437c7f3, 0xac2d8da1, 0x80008080, 0x1c1f0f13, 0xc80acac2, 0x2c2c0c20, 0xa82a8aa2, 0x34340430,
0xd012c2d2, 0x080b0b03, 0xec2ecee2, 0xe829c9e1, 0x5c1d4d51, 0x94148490, 0x18180810, 0xf838c8f0,
0x54174753, 0xac2e8ea2, 0x08080800, 0xc405c5c1, 0x10130313, 0xcc0dcdc1, 0x84068682, 0xb83989b1,
0xfc3fcff3, 0x7c3d4d71, 0xc001c1c1, 0x30310131, 0xf435c5f1, 0x880a8a82, 0x682a4a62, 0xb03181b1,
0xd011c1d1, 0x20200020, 0xd417c7d3, 0x00020202, 0x20220222, 0x04040400, 0x68284860, 0x70314171,
0x04070703, 0xd81bcbd3, 0x9c1d8d91, 0x98198991, 0x60214161, 0xbc3e8eb2, 0xe426c6e2, 0x58194951,
0xdc1dcdd1, 0x50114151, 0x90108090, 0xdc1cccd0, 0x981a8a92, 0xa02383a3, 0xa82b8ba3, 0xd010c0d0,
0x80018181, 0x0c0f0f03, 0x44074743, 0x181a0a12, 0xe023c3e3, 0xec2ccce0, 0x8c0d8d81, 0xbc3f8fb3,
0x94168692, 0x783b4b73, 0x5c1c4c50, 0xa02282a2, 0xa02181a1, 0x60234363, 0x20230323, 0x4c0d4d41,
0xc808c8c0, 0x9c1e8e92, 0x9c1c8c90, 0x383a0a32, 0x0c0c0c00, 0x2c2e0e22, 0xb83a8ab2, 0x6c2e4e62,
0x9c1f8f93, 0x581a4a52, 0xf032c2f2, 0x90128292, 0xf033c3f3, 0x48094941, 0x78384870, 0xcc0cccc0,
0x14150511, 0xf83bcbf3, 0x70304070, 0x74354571, 0x7c3f4f73, 0x34350531, 0x10100010, 0x00030303,
0x64244460, 0x6c2d4d61, 0xc406c6c2, 0x74344470, 0xd415c5d1, 0xb43484b0, 0xe82acae2, 0x08090901,
0x74364672, 0x18190911, 0xfc3ecef2, 0x40004040, 0x10120212, 0xe020c0e0, 0xbc3d8db1, 0x04050501,
0xf83acaf2, 0x00010101, 0xf030c0f0, 0x282a0a22, 0x5c1e4e52, 0xa82989a1, 0x54164652, 0x40034343,
0x84058581, 0x14140410, 0x88098981, 0x981b8b93, 0xb03080b0, 0xe425c5e1, 0x48084840, 0x78394971,
0x94178793, 0xfc3cccf0, 0x1c1e0e12, 0x80028282, 0x20210121, 0x8c0c8c80, 0x181b0b13, 0x5c1f4f53,
0x74374773, 0x54144450, 0xb03282b2, 0x1c1d0d11, 0x24250521, 0x4c0f4f43, 0x00000000, 0x44064642,
0xec2dcde1, 0x58184850, 0x50124252, 0xe82bcbe3, 0x7c3e4e72, 0xd81acad2, 0xc809c9c1, 0xfc3dcdf1,
0x30300030, 0x94158591, 0x64254561, 0x3c3c0c30, 0xb43686b2, 0xe424c4e0, 0xb83b8bb3, 0x7c3c4c70,
0x0c0e0e02, 0x50104050, 0x38390931, 0x24260622, 0x30320232, 0x84048480, 0x68294961, 0x90138393,
0x34370733, 0xe427c7e3, 0x24240420, 0xa42484a0, 0xc80bcbc3, 0x50134353, 0x080a0a02, 0x84078783,
0xd819c9d1, 0x4c0c4c40, 0x80038383, 0x8c0f8f83, 0xcc0ecec2, 0x383b0b33, 0x480a4a42, 0xb43787b3
};
private static int SS2[] = {
0xa1a82989, 0x81840585, 0xd2d416c6, 0xd3d013c3, 0x50541444, 0x111c1d0d, 0xa0ac2c8c, 0x21242505,
0x515c1d4d, 0x43400343, 0x10181808, 0x121c1e0e, 0x51501141, 0xf0fc3ccc, 0xc2c80aca, 0x63602343,
0x20282808, 0x40440444, 0x20202000, 0x919c1d8d, 0xe0e020c0, 0xe2e022c2, 0xc0c808c8, 0x13141707,
0xa1a42585, 0x838c0f8f, 0x03000303, 0x73783b4b, 0xb3b83b8b, 0x13101303, 0xd2d012c2, 0xe2ec2ece,
0x70703040, 0x808c0c8c, 0x333c3f0f, 0xa0a82888, 0x32303202, 0xd1dc1dcd, 0xf2f436c6, 0x70743444,
0xe0ec2ccc, 0x91941585, 0x03080b0b, 0x53541747, 0x505c1c4c, 0x53581b4b, 0xb1bc3d8d, 0x01000101,
0x20242404, 0x101c1c0c, 0x73703343, 0x90981888, 0x10101000, 0xc0cc0ccc, 0xf2f032c2, 0xd1d819c9,
0x202c2c0c, 0xe3e427c7, 0x72703242, 0x83800383, 0x93981b8b, 0xd1d011c1, 0x82840686, 0xc1c809c9,
0x60602040, 0x50501040, 0xa3a02383, 0xe3e82bcb, 0x010c0d0d, 0xb2b43686, 0x929c1e8e, 0x434c0f4f,
0xb3b43787, 0x52581a4a, 0xc2c406c6, 0x70783848, 0xa2a42686, 0x12101202, 0xa3ac2f8f, 0xd1d415c5,
0x61602141, 0xc3c003c3, 0xb0b43484, 0x41400141, 0x52501242, 0x717c3d4d, 0x818c0d8d, 0x00080808,
0x131c1f0f, 0x91981989, 0x00000000, 0x11181909, 0x00040404, 0x53501343, 0xf3f437c7, 0xe1e021c1,
0xf1fc3dcd, 0x72743646, 0x232c2f0f, 0x23242707, 0xb0b03080, 0x83880b8b, 0x020c0e0e, 0xa3a82b8b,
0xa2a02282, 0x626c2e4e, 0x93901383, 0x414c0d4d, 0x61682949, 0x707c3c4c, 0x01080909, 0x02080a0a,
0xb3bc3f8f, 0xe3ec2fcf, 0xf3f033c3, 0xc1c405c5, 0x83840787, 0x10141404, 0xf2fc3ece, 0x60642444,
0xd2dc1ece, 0x222c2e0e, 0x43480b4b, 0x12181a0a, 0x02040606, 0x21202101, 0x63682b4b, 0x62642646,
0x02000202, 0xf1f435c5, 0x92901282, 0x82880a8a, 0x000c0c0c, 0xb3b03383, 0x727c3e4e, 0xd0d010c0,
0x72783a4a, 0x43440747, 0x92941686, 0xe1e425c5, 0x22242606, 0x80800080, 0xa1ac2d8d, 0xd3dc1fcf,
0xa1a02181, 0x30303000, 0x33343707, 0xa2ac2e8e, 0x32343606, 0x11141505, 0x22202202, 0x30383808,
0xf0f434c4, 0xa3a42787, 0x41440545, 0x404c0c4c, 0x81800181, 0xe1e829c9, 0x80840484, 0x93941787,
0x31343505, 0xc3c80bcb, 0xc2cc0ece, 0x303c3c0c, 0x71703141, 0x11101101, 0xc3c407c7, 0x81880989,
0x71743545, 0xf3f83bcb, 0xd2d81aca, 0xf0f838c8, 0x90941484, 0x51581949, 0x82800282, 0xc0c404c4,
0xf3fc3fcf, 0x41480949, 0x31383909, 0x63642747, 0xc0c000c0, 0xc3cc0fcf, 0xd3d417c7, 0xb0b83888,
0x030c0f0f, 0x828c0e8e, 0x42400242, 0x23202303, 0x91901181, 0x606c2c4c, 0xd3d81bcb, 0xa0a42484,
0x30343404, 0xf1f031c1, 0x40480848, 0xc2c002c2, 0x636c2f4f, 0x313c3d0d, 0x212c2d0d, 0x40400040,
0xb2bc3e8e, 0x323c3e0e, 0xb0bc3c8c, 0xc1c001c1, 0xa2a82a8a, 0xb2b83a8a, 0x424c0e4e, 0x51541545,
0x33383b0b, 0xd0dc1ccc, 0x60682848, 0x737c3f4f, 0x909c1c8c, 0xd0d818c8, 0x42480a4a, 0x52541646,
0x73743747, 0xa0a02080, 0xe1ec2dcd, 0x42440646, 0xb1b43585, 0x23282b0b, 0x61642545, 0xf2f83aca,
0xe3e023c3, 0xb1b83989, 0xb1b03181, 0x939c1f8f, 0x525c1e4e, 0xf1f839c9, 0xe2e426c6, 0xb2b03282,
0x31303101, 0xe2e82aca, 0x616c2d4d, 0x535c1f4f, 0xe0e424c4, 0xf0f030c0, 0xc1cc0dcd, 0x80880888,
0x12141606, 0x32383a0a, 0x50581848, 0xd0d414c4, 0x62602242, 0x21282909, 0x03040707, 0x33303303,
0xe0e828c8, 0x13181b0b, 0x01040505, 0x71783949, 0x90901080, 0x62682a4a, 0x22282a0a, 0x92981a8a
};
private static int SS3[] = {
0x08303838, 0xc8e0e828, 0x0d212c2d, 0x86a2a426, 0xcfc3cc0f, 0xced2dc1e, 0x83b3b033, 0x88b0b838,
0x8fa3ac2f, 0x40606020, 0x45515415, 0xc7c3c407, 0x44404404, 0x4f636c2f, 0x4b63682b, 0x4b53581b,
0xc3c3c003, 0x42626022, 0x03333033, 0x85b1b435, 0x09212829, 0x80a0a020, 0xc2e2e022, 0x87a3a427,
0xc3d3d013, 0x81919011, 0x01111011, 0x06020406, 0x0c101c1c, 0x8cb0bc3c, 0x06323436, 0x4b43480b,
0xcfe3ec2f, 0x88808808, 0x4c606c2c, 0x88a0a828, 0x07131417, 0xc4c0c404, 0x06121416, 0xc4f0f434,
0xc2c2c002, 0x45414405, 0xc1e1e021, 0xc6d2d416, 0x0f333c3f, 0x0d313c3d, 0x8e828c0e, 0x88909818,
0x08202828, 0x4e424c0e, 0xc6f2f436, 0x0e323c3e, 0x85a1a425, 0xc9f1f839, 0x0d010c0d, 0xcfd3dc1f,
0xc8d0d818, 0x0b23282b, 0x46626426, 0x4a72783a, 0x07232427, 0x0f232c2f, 0xc1f1f031, 0x42727032,
0x42424002, 0xc4d0d414, 0x41414001, 0xc0c0c000, 0x43737033, 0x47636427, 0x8ca0ac2c, 0x8b83880b,
0xc7f3f437, 0x8da1ac2d, 0x80808000, 0x0f131c1f, 0xcac2c80a, 0x0c202c2c, 0x8aa2a82a, 0x04303434,
0xc2d2d012, 0x0b03080b, 0xcee2ec2e, 0xc9e1e829, 0x4d515c1d, 0x84909414, 0x08101818, 0xc8f0f838,
0x47535417, 0x8ea2ac2e, 0x08000808, 0xc5c1c405, 0x03131013, 0xcdc1cc0d, 0x86828406, 0x89b1b839,
0xcff3fc3f, 0x4d717c3d, 0xc1c1c001, 0x01313031, 0xc5f1f435, 0x8a82880a, 0x4a62682a, 0x81b1b031,
0xc1d1d011, 0x00202020, 0xc7d3d417, 0x02020002, 0x02222022, 0x04000404, 0x48606828, 0x41717031,
0x07030407, 0xcbd3d81b, 0x8d919c1d, 0x89919819, 0x41616021, 0x8eb2bc3e, 0xc6e2e426, 0x49515819,
0xcdd1dc1d, 0x41515011, 0x80909010, 0xccd0dc1c, 0x8a92981a, 0x83a3a023, 0x8ba3a82b, 0xc0d0d010,
0x81818001, 0x0f030c0f, 0x47434407, 0x0a12181a, 0xc3e3e023, 0xcce0ec2c, 0x8d818c0d, 0x8fb3bc3f,
0x86929416, 0x4b73783b, 0x4c505c1c, 0x82a2a022, 0x81a1a021, 0x43636023, 0x03232023, 0x4d414c0d,
0xc8c0c808, 0x8e929c1e, 0x8c909c1c, 0x0a32383a, 0x0c000c0c, 0x0e222c2e, 0x8ab2b83a, 0x4e626c2e,
0x8f939c1f, 0x4a52581a, 0xc2f2f032, 0x82929012, 0xc3f3f033, 0x49414809, 0x48707838, 0xccc0cc0c,
0x05111415, 0xcbf3f83b, 0x40707030, 0x45717435, 0x4f737c3f, 0x05313435, 0x00101010, 0x03030003,
0x44606424, 0x4d616c2d, 0xc6c2c406, 0x44707434, 0xc5d1d415, 0x84b0b434, 0xcae2e82a, 0x09010809,
0x46727436, 0x09111819, 0xcef2fc3e, 0x40404000, 0x02121012, 0xc0e0e020, 0x8db1bc3d, 0x05010405,
0xcaf2f83a, 0x01010001, 0xc0f0f030, 0x0a22282a, 0x4e525c1e, 0x89a1a829, 0x46525416, 0x43434003,
0x85818405, 0x04101414, 0x89818809, 0x8b93981b, 0x80b0b030, 0xc5e1e425, 0x48404808, 0x49717839,
0x87939417, 0xccf0fc3c, 0x0e121c1e, 0x82828002, 0x01212021, 0x8c808c0c, 0x0b13181b, 0x4f535c1f,
0x47737437, 0x44505414, 0x82b2b032, 0x0d111c1d, 0x05212425, 0x4f434c0f, 0x00000000, 0x46424406,
0xcde1ec2d, 0x48505818, 0x42525012, 0xcbe3e82b, 0x4e727c3e, 0xcad2d81a, 0xc9c1c809, 0xcdf1fc3d,
0x00303030, 0x85919415, 0x45616425, 0x0c303c3c, 0x86b2b436, 0xc4e0e424, 0x8bb3b83b, 0x4c707c3c,
0x0e020c0e, 0x40505010, 0x09313839, 0x06222426, 0x02323032, 0x84808404, 0x49616829, 0x83939013,
0x07333437, 0xc7e3e427, 0x04202424, 0x84a0a424, 0xcbc3c80b, 0x43535013, 0x0a02080a, 0x87838407,
0xc9d1d819, 0x4c404c0c, 0x83838003, 0x8f838c0f, 0xcec2cc0e, 0x0b33383b, 0x4a42480a, 0x87b3b437
};
private static int[] KC = {
0x9e3779b9, 0x3c6ef373, 0x78dde6e6, 0xf1bbcdcc, 0xe3779b99, 0xc6ef3733, 0x8dde6e67, 0x1bbcdccf,
0x3779b99e, 0x6ef3733c, 0xdde6e678, 0xbbcdccf1, 0x779b99e3, 0xef3733c6, 0xde6e678d, 0xbcdccf1b
};
/* 시스템의 Endian을 정의 */
private static Boolean LITTLE = true;
// private static Boolean BIG = false;
/* C의 Define 대신 사용 */
/* System의 Endian에 따라 선택적으로 사용 */
private static Boolean ENDIAN = LITTLE; // Intel 80x86, DEC VAX, DEC PDP-11
//private static Bool ENDIAN = BIG; // IBM370, Motorola 68000, Pyramid (대부분의 RISC 기반)
/* 초기 환경 변수 */
private static int NoRounds = 16;
// private int NoRoundKeys = 32; //(NoRounds*2)
// private int SeedBlockSize = 16; // in bytes
// private int SeedBlockLen = 128; // in bits
/* Encryption/Decryption */
private static int GetB0(int A){ return (int)(0x000000ff&(A) ); };
private static int GetB1(int A){ return (int)(0x000000ff&((A)>>>8)); };
private static int GetB2(int A){ return (int)(0x000000ff&((A)>>>16)); };
private static int GetB3(int A){ return (int)(0x000000ff&((A)>>>24)); };
private static void EndianChange(int dws[]) { dws[0] = (dws[0]>>>24) | (dws[0]<<24) | ((dws[0]<<8)&0x00ff0000)|((dws[0]>>>8)&0x0000ff00); };
private static int EndianChange(int dws) { return (dws>>>24) | (dws<<24) | ((dws<<8)&0x00ff0000)|((dws>>>8)&0x0000ff00); };
/* Round Function */
private static void SeedRound(int L0[], int L1[], int R0[], int R1[], int K[])
{
int T0, T1;
long T00=0, T11=0;
T0 = R0[0] ^ K[0];
T1 = R1[0] ^ K[1];
T1 ^= T0;
T00 = (T0<0) ? (long)(T0 & 0x7fffffff)|(long)(0x80000000) : (long)(T0);
T1 = SS0[GetB0(T1)] ^ SS1[GetB1(T1)] ^ SS2[GetB2(T1)] ^ SS3[GetB3(T1)];
T11 = (T1<0) ? (long)(T1 & 0x7fffffff)|(long)(0x80000000) : (long)(T1);
T00 += T11;
T0 = SS0[GetB0((int)T00)] ^ SS1[GetB1((int)T00)] ^ SS2[GetB2((int)T00)] ^ SS3[GetB3((int)T00)];
T00 = (T0<0) ? (long)(T0 & 0x7fffffff)|(long)(0x80000000) : (long)(T0);
T11 += T00;
T1 = SS0[GetB0((int)T11)] ^ SS1[GetB1((int)T11)] ^ SS2[GetB2((int)T11)] ^ SS3[GetB3((int)T11)];
T11 = (T1<0) ? (long)(T1 & 0x7fffffff)|(long)(0x80000000) : (long)(T1);
T00 += T11;
L0[0] ^= (int)T00; L1[0] ^= (int)T11; // return L0, L1
};
/* Encrypt */
public static void SeedEncrypt(byte pbData[], int pdwRoundKey[], byte outData[])
{
int L0[] = new int[1]; int L1[] = new int[1];
int R0[] = new int[1]; int R1[] = new int[1];
L0[0] = 0x0; L1[0] = 0x0; R0[0] = 0x0; R1[0] = 0x0;
int K[] = new int[2];
int nCount = 0;
L0[0] = ((int)pbData[0]&0x000000ff);
L0[0] = ((L0[0])<<8)^((int)pbData[1]&0x000000ff);
L0[0] = ((L0[0])<<8)^((int)pbData[2]&0x000000ff);
L0[0] = ((L0[0])<<8)^((int)pbData[3]&0x000000ff);
L1[0] = ((int)pbData[4]&0x000000ff);
L1[0] = ((L1[0])<<8)^((int)pbData[5]&0x000000ff);
L1[0] = ((L1[0])<<8)^((int)pbData[6]&0x000000ff);
L1[0] = ((L1[0])<<8)^((int)pbData[7]&0x000000ff);
R0[0] = ((int)pbData[8]&0x000000ff);
R0[0] = ((R0[0])<<8)^((int)pbData[9]&0x000000ff);
R0[0] = ((R0[0])<<8)^((int)pbData[10]&0x000000ff);
R0[0] = ((R0[0])<<8)^((int)pbData[11]&0x000000ff);
R1[0] = ((int)pbData[12]&0x000000ff);
R1[0] = ((R1[0])<<8)^((int)pbData[13]&0x000000ff);
R1[0] = ((R1[0])<<8)^((int)pbData[14]&0x000000ff);
R1[0] = ((R1[0])<<8)^((int)pbData[15]&0x000000ff);
if (!ENDIAN) {EndianChange(L0); EndianChange(L1); EndianChange(R0); EndianChange(R1);};
K[0] = pdwRoundKey[nCount++]; K[1] = pdwRoundKey[nCount++];
SeedRound(L0, L1, R0, R1, K); /* 1 */
K[0] = pdwRoundKey[nCount++]; K[1] = pdwRoundKey[nCount++];
SeedRound(R0, R1, L0, L1, K); /* 2 */
K[0] = pdwRoundKey[nCount++]; K[1] = pdwRoundKey[nCount++];
SeedRound(L0, L1, R0, R1, K); /* 3 */
K[0] = pdwRoundKey[nCount++]; K[1] = pdwRoundKey[nCount++];
SeedRound(R0, R1, L0, L1, K); /* 4 */
K[0] = pdwRoundKey[nCount++]; K[1] = pdwRoundKey[nCount++];
SeedRound(L0, L1, R0, R1, K); /* 5 */
K[0] = pdwRoundKey[nCount++]; K[1] = pdwRoundKey[nCount++];
SeedRound(R0, R1, L0, L1, K); /* 6 */
K[0] = pdwRoundKey[nCount++]; K[1] = pdwRoundKey[nCount++];
SeedRound(L0, L1, R0, R1, K); /* 7 */
K[0] = pdwRoundKey[nCount++]; K[1] = pdwRoundKey[nCount++];
SeedRound(R0, R1, L0, L1, K); /* 8 */
K[0] = pdwRoundKey[nCount++]; K[1] = pdwRoundKey[nCount++];
SeedRound(L0, L1, R0, R1, K); /* 9 */
K[0] = pdwRoundKey[nCount++]; K[1] = pdwRoundKey[nCount++];
SeedRound(R0, R1, L0, L1, K); /* 10 */
K[0] = pdwRoundKey[nCount++]; K[1] = pdwRoundKey[nCount++];
SeedRound(L0, L1, R0, R1, K); /* 11 */
K[0] = pdwRoundKey[nCount++]; K[1] = pdwRoundKey[nCount++];
SeedRound(R0, R1, L0, L1, K); /* 12 */
if (NoRounds == 16)
{
K[0] = pdwRoundKey[nCount++]; K[1] = pdwRoundKey[nCount++];
SeedRound(L0, L1, R0, R1, K); /* 13 */
K[0] = pdwRoundKey[nCount++]; K[1] = pdwRoundKey[nCount++];
SeedRound(R0, R1, L0, L1, K); /* 14 */
K[0] = pdwRoundKey[nCount++]; K[1] = pdwRoundKey[nCount++];
SeedRound(L0, L1, R0, R1, K); /* 15 */
K[0] = pdwRoundKey[nCount++]; K[1] = pdwRoundKey[nCount++];
SeedRound(R0, R1, L0, L1, K); /* 16 */
}
if (!ENDIAN) {EndianChange(L0); EndianChange(L1); EndianChange(R0); EndianChange(R1);};
for (int i=0; i<4; i++)
{
outData[i ] = (byte)(((R0[0])>>>(8*(3-i)))&0xff);
outData[4+i ] = (byte)(((R1[0])>>>(8*(3-i)))&0xff);
outData[8+i ] = (byte)(((L0[0])>>>(8*(3-i)))&0xff);
outData[12+i] = (byte)(((L1[0])>>>(8*(3-i)))&0xff);
}
}
/* Decrypt */
/* same as encrypt, except that round keys are applied in reverse order. */
public static void SeedDecrypt(byte pbData[], int pdwRoundKey[], byte outData[])
{
int L0[] = new int[1]; int L1[] = new int[1];
int R0[] = new int[1]; int R1[] = new int[1];
int K[] = new int[2];
L0[0] = 0x0; L1[0] = 0x0; R0[0] = 0x0; R1[0] = 0x0;
int nCount = 31;
L0[0] = ((int)pbData[0]&0x000000ff);
L0[0] = ((L0[0])<<8)^((int)pbData[1]&0x000000ff);
L0[0] = ((L0[0])<<8)^((int)pbData[2]&0x000000ff);
L0[0] = ((L0[0])<<8)^((int)pbData[3]&0x000000ff);
L1[0] = ((int)pbData[4]&0x000000ff);
L1[0] = ((L1[0])<<8)^((int)pbData[5]&0x000000ff);
L1[0] = ((L1[0])<<8)^((int)pbData[6]&0x000000ff);
L1[0] = ((L1[0])<<8)^((int)pbData[7]&0x000000ff);
R0[0] = ((int)pbData[8]&0x000000ff);
R0[0] = ((R0[0])<<8)^((int)pbData[9]&0x000000ff);
R0[0] = ((R0[0])<<8)^((int)pbData[10]&0x000000ff);
R0[0] = ((R0[0])<<8)^((int)pbData[11]&0x000000ff);
R1[0] = ((int)pbData[12]&0x000000ff);
R1[0] = ((R1[0])<<8)^((int)pbData[13]&0x000000ff);
R1[0] = ((R1[0])<<8)^((int)pbData[14]&0x000000ff);
R1[0] = ((R1[0])<<8)^((int)pbData[15]&0x000000ff);
if (!ENDIAN) {EndianChange(L0); EndianChange(L1); EndianChange(R0); EndianChange(R1);};
if (NoRounds == 16)
{
K[1] = pdwRoundKey[nCount--]; K[0] = pdwRoundKey[nCount--];
SeedRound(L0, L1, R0, R1, K); /* 1 */
K[1] = pdwRoundKey[nCount--]; K[0] = pdwRoundKey[nCount--];
SeedRound(R0, R1, L0, L1, K); /* 2 */
K[1] = pdwRoundKey[nCount--]; K[0] = pdwRoundKey[nCount--];
SeedRound(L0, L1, R0, R1, K); /* 3 */
K[1] = pdwRoundKey[nCount--]; K[0] = pdwRoundKey[nCount--];
SeedRound(R0, R1, L0, L1, K); /* 4 */
}
K[1] = pdwRoundKey[nCount--]; K[0] = pdwRoundKey[nCount--];
SeedRound(L0, L1, R0, R1, K); /* 5 */
K[1] = pdwRoundKey[nCount--]; K[0] = pdwRoundKey[nCount--];
SeedRound(R0, R1, L0, L1, K); /* 6 */
K[1] = pdwRoundKey[nCount--]; K[0] = pdwRoundKey[nCount--];
SeedRound(L0, L1, R0, R1, K); /* 7 */
K[1] = pdwRoundKey[nCount--]; K[0] = pdwRoundKey[nCount--];
SeedRound(R0, R1, L0, L1, K); /* 8 */
K[1] = pdwRoundKey[nCount--]; K[0] = pdwRoundKey[nCount--];
SeedRound(L0, L1, R0, R1, K); /* 9 */
K[1] = pdwRoundKey[nCount--]; K[0] = pdwRoundKey[nCount--];
SeedRound(R0, R1, L0, L1, K); /* 10 */
K[1] = pdwRoundKey[nCount--]; K[0] = pdwRoundKey[nCount--];
SeedRound(L0, L1, R0, R1, K); /* 11 */
K[1] = pdwRoundKey[nCount--]; K[0] = pdwRoundKey[nCount--];
SeedRound(R0, R1, L0, L1, K); /* 12 */
K[1] = pdwRoundKey[nCount--]; K[0] = pdwRoundKey[nCount--];
SeedRound(L0, L1, R0, R1, K); /* 13 */
K[1] = pdwRoundKey[nCount--]; K[0] = pdwRoundKey[nCount--];
SeedRound(R0, R1, L0, L1, K); /* 14 */
K[1] = pdwRoundKey[nCount--]; K[0] = pdwRoundKey[nCount--];
SeedRound(L0, L1, R0, R1, K); /* 15 */
K[1] = pdwRoundKey[nCount--]; K[0] = pdwRoundKey[nCount];
SeedRound(R0, R1, L0, L1, K); /* 16 */
if (!ENDIAN) {EndianChange(L0); EndianChange(L1); EndianChange(R0); EndianChange(R1);};
for (int i=0; i<4; i++)
{
outData[i ] = (byte)(((R0[0])>>>(8*(3-i)))&0xff);
outData[4+i ] = (byte)(((R1[0])>>>(8*(3-i)))&0xff);
outData[8+i ] = (byte)(((L0[0])>>>(8*(3-i)))&0xff);
outData[12+i] = (byte)(((L1[0])>>>(8*(3-i)))&0xff);
}
}
private static void EncRoundKeyUpdate0(int K[], int A[], int B[], int C[], int D[], int Z)
{
int T0;
int T00, T11;
T0 = A[0];
A[0] = (A[0]>>>8) ^ (B[0]<<24);
B[0] = (B[0]>>>8) ^ (T0<<24);
T00 = (int)A[0] + (int)C[0] - (int)KC[Z];
T11 = (int)B[0] + (int)KC[Z] - (int)D[0];
K[0] = SS0[GetB0((int)T00)] ^ SS1[GetB1((int)T00)] ^ SS2[GetB2((int)T00)] ^ SS3[GetB3((int)T00)];
K[1] = SS0[GetB0((int)T11)] ^ SS1[GetB1((int)T11)] ^ SS2[GetB2((int)T11)] ^ SS3[GetB3((int)T11)];
}
private static void EncRoundKeyUpdate1(int K[], int A[], int B[], int C[], int D[], int Z)
{
int T0;
int T00, T11;
T0 = C[0];
C[0] = (C[0]<<8) ^ (D[0]>>>24);
D[0] = (D[0]<<8) ^ (T0>>>24);
T00 = (int)A[0] + (int)C[0] - (int)KC[Z];
T11 = (int)B[0] + (int)KC[Z] - (int)D[0];
K[0] = SS0[GetB0((int)T00)] ^ SS1[GetB1((int)T00)] ^ SS2[GetB2((int)T00)] ^ SS3[GetB3((int)T00)];
K[1] = SS0[GetB0((int)T11)] ^ SS1[GetB1((int)T11)] ^ SS2[GetB2((int)T11)] ^ SS3[GetB3((int)T11)];
}
public static void SeedEncRoundKey(int pdwRoundKey[], byte pbUserKey[])
{
int A[] = new int[1];
int B[] = new int[1];
int C[] = new int[1];
int D[] = new int[1];
int K[] = new int[2];
int T0, T1;
int nCount = 2;
A[0] = ((int)pbUserKey[0]&0x000000ff);
A[0] = (A[0]<<8)^((int)pbUserKey[1]&0x000000ff);
A[0] = (A[0]<<8)^((int)pbUserKey[2]&0x000000ff);
A[0] = (A[0]<<8)^((int)pbUserKey[3]&0x000000ff);
B[0] = ((int)pbUserKey[4]&0x000000ff);
B[0] = (B[0]<<8)^((int)pbUserKey[5]&0x000000ff);
B[0] = (B[0]<<8)^((int)pbUserKey[6]&0x000000ff);
B[0] = (B[0]<<8)^((int)pbUserKey[7]&0x000000ff);
C[0] = ((int)pbUserKey[8]&0x000000ff);
C[0] = (C[0]<<8)^((int)pbUserKey[9]&0x000000ff);
C[0] = (C[0]<<8)^((int)pbUserKey[10]&0x000000ff);
C[0] = (C[0]<<8)^((int)pbUserKey[11]&0x000000ff);
D[0] = ((int)pbUserKey[12]&0x000000ff);
D[0] = (D[0]<<8)^((int)pbUserKey[13]&0x000000ff);
D[0] = (D[0]<<8)^((int)pbUserKey[14]&0x000000ff);
D[0] = (D[0]<<8)^((int)pbUserKey[15]&0x000000ff);
if (!ENDIAN) {A[0]=EndianChange(A[0]); B[0]=EndianChange(B[0]); C[0]=EndianChange(C[0]); D[0]=EndianChange(D[0]);};
T0 = (int)A[0] + (int)C[0] - (int)KC[0];
T1 = (int)B[0] - (int)D[0] + (int)KC[0];
pdwRoundKey[0] = SS0[GetB0((int)T0)] ^ SS1[GetB1((int)T0)] ^ SS2[GetB2((int)T0)] ^ SS3[GetB3((int)T0)];
pdwRoundKey[1] = SS0[GetB0((int)T1)] ^ SS1[GetB1((int)T1)] ^ SS2[GetB2((int)T1)] ^ SS3[GetB3((int)T1)];
EncRoundKeyUpdate0(K, A, B, C, D, 1 );
pdwRoundKey[nCount++] = K[0]; pdwRoundKey[nCount++] = K[1];
EncRoundKeyUpdate1(K, A, B, C, D, 2 );
pdwRoundKey[nCount++] = K[0]; pdwRoundKey[nCount++] = K[1];
EncRoundKeyUpdate0(K, A, B, C, D, 3 );
pdwRoundKey[nCount++] = K[0]; pdwRoundKey[nCount++] = K[1];
EncRoundKeyUpdate1(K, A, B, C, D, 4 );
pdwRoundKey[nCount++] = K[0]; pdwRoundKey[nCount++] = K[1];
EncRoundKeyUpdate0(K, A, B, C, D, 5 );
pdwRoundKey[nCount++] = K[0]; pdwRoundKey[nCount++] = K[1];
EncRoundKeyUpdate1(K, A, B, C, D, 6 );
pdwRoundKey[nCount++] = K[0]; pdwRoundKey[nCount++] = K[1];
EncRoundKeyUpdate0(K, A, B, C, D, 7 );
pdwRoundKey[nCount++] = K[0]; pdwRoundKey[nCount++] = K[1];
EncRoundKeyUpdate1(K, A, B, C, D, 8 );
pdwRoundKey[nCount++] = K[0]; pdwRoundKey[nCount++] = K[1];
EncRoundKeyUpdate0(K, A, B, C, D, 9 );
pdwRoundKey[nCount++] = K[0]; pdwRoundKey[nCount++] = K[1];
EncRoundKeyUpdate1(K, A, B, C, D, 10);
pdwRoundKey[nCount++] = K[0]; pdwRoundKey[nCount++] = K[1];
EncRoundKeyUpdate0(K, A, B, C, D, 11);
pdwRoundKey[nCount++] = K[0]; pdwRoundKey[nCount++] = K[1];
if (NoRounds == 16)
{
EncRoundKeyUpdate1(K, A, B, C, D, 12);
pdwRoundKey[nCount++] = K[0]; pdwRoundKey[nCount++] = K[1];
EncRoundKeyUpdate0(K, A, B, C, D, 13);
pdwRoundKey[nCount++] = K[0]; pdwRoundKey[nCount++] = K[1];
EncRoundKeyUpdate1(K, A, B, C, D, 14);
pdwRoundKey[nCount++] = K[0]; pdwRoundKey[nCount++] = K[1];
EncRoundKeyUpdate0(K, A, B, C, D, 15);
pdwRoundKey[nCount++] = K[0]; pdwRoundKey[nCount++] = K[1];
}
}
public static byte[] encrypt(byte[] bytes) {
return bytes;
}
public static byte[] decrypt(byte[] bytes) {
return bytes;
}
// public static void main(String[] args) throws Exception {
// int pdwRoundKey[] = new int[32];
// byte pbUserKey[] = {(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,
// (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00};
// byte pbData[] = {(byte)0x00, (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07,
// (byte)0x08, (byte)0x09, (byte)0x0A, (byte)0x0B, (byte)0x0C, (byte)0x0D, (byte)0x0E, (byte)0x0F};
//
// byte pbCipher[] = new byte[16];
// byte pbPlain[] = new byte[16];
//
// System.out.print("[ Test SEED reference code ]" + "\n");
// System.out.print("\n\n");
//
// pbData = "1234567890123456".getBytes();
//
// /**
// * round key
// */
// SeedEncRoundKey(pdwRoundKey, pbUserKey);
//
// /**
// * encrypt
// */
// SeedEncrypt(pbData, pdwRoundKey, pbCipher);
//
// System.out.println("[ Test Encrypt mode ] ##################################");
// System.out.println("Key : " + CommonLib.hexDump(pbUserKey));
// System.out.println("Plaintext : " + CommonLib.hexDump(pbData));
// System.out.println("Ciphertext : " + CommonLib.hexDump(pbCipher));
//
// /**
// * decrypt
// */
// SeedDecrypt(pbCipher, pdwRoundKey, pbPlain);
//
// System.out.println("[ Test Decrypt mode ] ##################################");
// System.out.println("Key : " + CommonLib.hexDump(pbUserKey));
// System.out.println("Ciphertext : " + CommonLib.hexDump(pbCipher));
// System.out.println("Plaintext : " + CommonLib.hexDump(pbPlain));
// }
}
@@ -0,0 +1,47 @@
package com.eactive.eai.transformer.function.crypto;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
public class SeedDecrypt extends PostfixMathCommand {
public SeedDecrypt() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
inStack.push(null);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[] 또는 String이 아닙니다. : " + param);
}
try {
inStack.push(value);
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,49 @@
package com.eactive.eai.transformer.function.crypto;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
//import com.eactive.eai.adapter.socket2.protocol.egseed.handshake.EgseedCodec;
public class SeedEncrypt extends PostfixMathCommand {
public SeedEncrypt() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object param = inStack.pop();
byte[] value = null;
if (param instanceof String) {
value = ((String) param).getBytes();
} else if (param instanceof byte[]) {
value = (byte[]) param;
} else if (param instanceof Double) {
if (((Double) param).doubleValue() == Math.round(((Double) param).doubleValue())) {
value = new Long(Math.round(((Double) param).doubleValue())).toString().getBytes();
} else {
value =((Number) param).toString().getBytes();
}
} else if (param instanceof Number) {
value = ((Number) param).toString().getBytes();
} else if (param == null) {
inStack.push(null);
return;
} else {
throw new ParseException("Function의 파라미터 인수가 byte[] 또는 String이 아닙니다. : " + param);
}
try {
inStack.push(value);
} catch (Exception e) {
//throw new ExecutionException(e.getMessage(), parameters, e);
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,38 @@
package com.eactive.eai.transformer.function.crypto;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.function.util.XdbCrypto;
public class XdbDecrypt extends PostfixMathCommand {
public XdbDecrypt() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object text = inStack.pop();
/**
* check text
*/
if (!(text instanceof String))
throw new ParseException("1st parameter (data) must be String data type");
String value = (String)text;
/**
* encrypt
*/
try {
inStack.push(XdbCrypto.getInstance().decrypt(value));
} catch (Exception e) {
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,38 @@
package com.eactive.eai.transformer.function.crypto;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.transformer.function.util.XdbCrypto;
public class XdbEncrypt extends PostfixMathCommand {
public XdbEncrypt() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object text = inStack.pop();
/**
* check text
*/
if (!(text instanceof String))
throw new ParseException("1st parameter (data) must be String data type");
String value = (String)text;
/**
* encrypt
*/
try {
inStack.push(XdbCrypto.getInstance().encrypt(value));
} catch (Exception e) {
throw new ParseException(e.getMessage(), e);
}
}
}
@@ -0,0 +1,39 @@
package com.eactive.eai.transformer.function.generic;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
public class BytesToDouble extends PostfixMathCommand {
public BytesToDouble() {
numberOfParameters = 1;
}
// Byte 문자를 Double 형 Binary(8Bytes) 로
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object p1 = inStack.pop();
double d = 0;
if (p1 instanceof byte[]) {
d = Double.parseDouble(new String((byte[]) p1));
} else if (p1 instanceof String) {
d = Double.parseDouble((String) p1);
} else if (p1 instanceof Number) {
d = ((Number) p1).doubleValue();
} else {
throw new ParseException("Invalid parameter type");
}
ByteBuffer buff = ByteBuffer.allocate(Double.SIZE / 8);
buff.putDouble(d);
buff.order(ByteOrder.BIG_ENDIAN);
inStack.push(buff.array());
}
}
@@ -0,0 +1,40 @@
package com.eactive.eai.transformer.function.generic;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
public class BytesToInteger extends PostfixMathCommand {
public BytesToInteger() {
numberOfParameters = 1;
}
// Byte 문자를 Integer 형 Binary(4Bytes)로
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object p1 = inStack.pop();
int i = 0;
if (p1 instanceof byte[]) {
i = Integer.parseInt(new String((byte[]) p1));
} else if (p1 instanceof String) {
i = Integer.parseInt((String) p1);
} else if (p1 instanceof Number) {
i = ((Number) p1).intValue();
} else {
throw new ParseException("Invalid parameter type");
}
byte[] bytes = new byte[] {
(byte)(i >>> 24),
(byte)(i >>> 16),
(byte)(i >>> 8),
(byte) i};
inStack.push(bytes);
}
}
@@ -0,0 +1,36 @@
package com.eactive.eai.transformer.function.generic;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
public class BytesToShort extends PostfixMathCommand {
public BytesToShort() {
numberOfParameters = 1;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object p1 = inStack.pop();
int i = 0;
if (p1 instanceof byte[]) {
i = Integer.parseInt(new String((byte[]) p1));
} else if (p1 instanceof String) {
i = Integer.parseInt((String) p1);
} else if (p1 instanceof Number) {
i = ((Number) p1).intValue();
} else {
throw new ParseException("Invalid parameter type");
}
byte[] bytes = new byte[] {
(byte)(i >>> 8),
(byte) i};
inStack.push(bytes);
}
}
@@ -0,0 +1,47 @@
package com.eactive.eai.transformer.function.generic;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
public class DoubleToBytes extends PostfixMathCommand {
public DoubleToBytes() {
numberOfParameters = 1;
}
// Double 형 Binary(8Bytes) 를 Byte 문자 로
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object p1 = inStack.pop();
if (p1 instanceof byte[]) {
byte[] bytes = (byte[]) p1;
if (bytes.length != 8)
throw new ParseException("'DoubleToBytes' function argument must be 8 bytes binary");
final int size = Double.SIZE / 8;
ByteBuffer buff = ByteBuffer.allocate(size);
final byte[] newBytes = new byte[size];
for (int i = 0; i < size; i++) {
if (i + bytes.length < size) {
newBytes[i] = (byte) 0x00;
}
else {
newBytes[i] = bytes[i + bytes.length - size];
}
}
buff = ByteBuffer.wrap(newBytes);
buff.order(ByteOrder.BIG_ENDIAN);
inStack.push(new Double(buff.getDouble()));
} else {
throw new ParseException("Invalid parameter type");
}
}
}
@@ -0,0 +1,36 @@
package com.eactive.eai.transformer.function.generic;
import java.util.Stack;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
public class IntegerToBytes extends PostfixMathCommand {
public IntegerToBytes() {
numberOfParameters = 1;
}
// Integer 형 Binary(4Bytes) 를 Byte 문자 로
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object p1 = inStack.pop();
if (p1 instanceof byte[]) {
byte[] bytes = (byte[]) p1;
if (bytes.length != 4)
throw new ParseException("'IntegerToBytes' function argument must be 4 bytes binary");
int i = (bytes[0] << 24)
+ ((bytes[1] & 0xFF) << 16)
+ ((bytes[2] & 0xFF) << 8)
+ (bytes[3] & 0xFF);
inStack.push(new Integer(i));
} else {
throw new ParseException("Invalid parameter type");
}
}
}
@@ -0,0 +1,44 @@
package com.eactive.eai.transformer.function.generic;
import java.util.Stack;
import org.apache.commons.lang3.StringUtils;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
public class LeftPad extends PostfixMathCommand {
public LeftPad() {
numberOfParameters = 3;
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);
Object p3 = inStack.pop();
if (p3 instanceof String) {
String str3 = (String) p3;
Object p2 = inStack.pop();
if (p2 instanceof Number) {
int _p2 = ((Number) p2).intValue();
Object p1 = inStack.pop();
if (p1 instanceof String) {
String str1 = (String) p1;
inStack.push(StringUtils.leftPad(str1, _p2, str3));
} else if (p1 instanceof byte[]) {
byte[] bytes = (byte[]) p1;
inStack.push(StringUtils.leftPad(new String(bytes), _p2, str3));
} else {
throw new ParseException("Invalid parameter type, p1 is not string/bytes");
}
} else {
throw new ParseException("Invalid parameter type, p2 is not number");
}
} else {
throw new ParseException("Invalid parameter type, p3 is not string");
}
}
}

Some files were not shown because too many files have changed in this diff Show More