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
+233
View File
@@ -0,0 +1,233 @@
gradle.properties
# Package Files #
*.war
src/main/generated
# Eclipse #
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
.classpath
.project
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Annotation Processing
.apt_generated/
.apt_generated_test/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
# Uncomment this line if you wish to ignore the project description file.
# Typically, this file would be tracked if it contains build/dependency configurations:
#.project
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
.idea
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
.idea/**/sonarlint/
# SonarQube Plugin
.idea/**/sonarIssues.xml
# Markdown Navigator plugin
.idea/**/markdown-navigator.xml
.idea/**/markdown-navigator/
### Java ###
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### Gradle ###
.gradle
build/
# Ignore Gradle GUI config
gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Cache of project
.gradletasknamecache
# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
# gradle/wrapper/gradle-wrapper.properties
### Gradle Patch ###
**/build/
# End of https://www.gitignore.io/api/java,macos,gradle,intellij
/EAISIMWeb/
/.apt_generated_tests/
+167
View File
@@ -0,0 +1,167 @@
plugins {
id 'java-library'
id 'maven-publish'
id 'eclipse-wtp'
id 'idea'
id 'com.diffplug.eclipse.apt' version '3.41.1'
}
group 'com.eactive'
version '4.5.1-SNAPSHOT'
def nexusUrl = "https://nexus.eactive.synology.me:8090"
def springVersion = "5.3.27"
def queryDslVersion = "5.0.0"
def hibernateVersion = "5.6.15.Final"
def generatedJavaDir = "$buildDir/generated/java"
java {
toolchain {
languageVersion = JavaLanguageVersion.of(8)
}
}
compileJava {
options.encoding = 'UTF-8'
sourceSets.main.java { srcDir generatedJavaDir }
options.generatedSourceOutputDirectory = project.file(generatedJavaDir)
aptOptions {
processorArgs = [ 'querydsl.generatedAnnotationClass' : 'com.querydsl.core.annotations.Generated' ]
}
}
jar {
exclude '**/persistence.xml'
}
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
dependencies {
// project > properties > Java Compiler > Annoation Processing
annotationProcessor "org.projectlombok:lombok:1.18.28", "org.projectlombok:lombok-mapstruct-binding:0.2.0", "org.mapstruct:mapstruct-processor:1.5.5.Final"
annotationProcessor "com.querydsl:querydsl-apt:${queryDslVersion}:jpa", "jakarta.persistence:jakarta.persistence-api:2.2.3", "jakarta.annotation:jakarta.annotation-api:1.3.5"
api project(':elink-online-core')
compileOnly fileTree(dir: 'libs', include: ['*.jar'])
api 'commons-collections:commons-collections:3.2.2'
api 'org.apache.poi:poi-excelant:3.9'
api group: 'org.apache.commons', name: 'commons-pool2', version: '2.11.1'
api 'commons-codec:commons-codec:1.15'
//api group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-xml', version: '2.13.1'
compileOnly group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-xml', version: '2.13.1'
compileOnly group: 'xalan', name: 'xalan', version: '2.6.0'
api 'net.sf.j8583:j8583:1.18.0'
//
// //삼성페이 penta
//api 'com.eactive:scphost:1.0'
//api 'com.eactive:xdsp_java:1.0'
//api 'com.eactive:jep-4.j18-md:1.0'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
testRuntimeOnly 'com.h2database:h2:2.1.214'
testImplementation 'org.springframework.boot:spring-boot-starter-test:2.6.15'
testImplementation 'org.junit.platform:junit-platform-suite-api:1.8.2'
testImplementation 'org.junit.platform:junit-platform-launcher:1.8.2'
//testImplementation files("libs/json-simple-1.1.1-custom-1.2.jar")
//testImplementation files("libs/jep-4.j18-md-1.0.jar")
testImplementation fileTree(dir: 'libs', include: ['*.jar'])
testImplementation group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-xml', version: '2.13.1'
testImplementation 'junit:junit:4.4'
}
test {
useJUnitPlatform()
}
publishing {
repositories {
maven {
name = 'eactiveRepository'
def releasesRepoUrl = "${nexusUrl}/repository/maven-releases/"
def snapshotsRepoUrl = "${nexusUrl}/repository/maven-snapshots/"
url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl
credentials(PasswordCredentials)
}
}
publications {
mavenJava(MavenPublication) {
from components.java
pom {
description = "eLink Transformer module"
licenses {
license {
name = "Commercial License"
url = "http://eactive.co.kr"
}
}
}
}
}
}
task sourcesJar(type: Jar, dependsOn: classes) {
archiveClassifier = 'sources'
from sourceSets.main.allSource
}
artifacts {
archives sourcesJar
}
configurations.all {
resolutionStrategy {
// 동적 버전 탐색을 10분 캐시
cacheDynamicVersionsFor 10, 'minutes'
// 변하는 모듈(Changing Module)을 캐시하지 않음
cacheChangingModulesFor 0, 'seconds'
}
}
task settingEclipseEncoding {
if (project.file('.settings').exists()) {
File f = file('.settings/org.eclipse.core.resources.prefs')
f.write('eclipse.preferences.version=1\n')
f.append('encoding/<project>=utf-8')
}
}
task initDirs() {
file(generatedJavaDir).mkdirs()
}
eclipse {
synchronizationTasks settingEclipseEncoding, initDirs
jdt {
apt {
// generated 된 패스 경로를 .setting/org.eclipse.jdt.apt.core.prefs 의 org.eclipse.jdt.apt.genSrcDir에 적용한다.
// project > properties > Java Compiler > Annoation Processing 화면에서 확인 가능하다.
genSrcDir = file(generatedJavaDir)
}
}
project {
natures = ['org.eclipse.buildship.core.gradleprojectnature',
'org.eclipse.jdt.core.javanature',
'org.eclipse.wst.common.project.facet.core.nature',
'org.eclipse.wst.common.modulecore.ModuleCoreNature',
'org.eclipse.jem.workbench.JavaEMFNature']
buildCommand 'org.eclipse.buildship.core.gradleprojectbuilder'
buildCommand 'org.eclipse.wst.validation.validationbuilder'
buildCommand 'org.eclipse.wst.common.project.facet.core.builder'
buildCommand 'org.eclipse.jdt.core.javabuilder'
}
}
+87
View File
@@ -0,0 +1,87 @@
################################################################################
# JDBC PROPERTIES
################################################################################
jdbc.driver=oracle.jdbc.driver.OracleDriver
#jdbc.driver=com.tmax.tibero.jdbc.TbDriver
#jdbc.driver=com.ibm.db2.jcc.DB2Driver
jdbc.debug=true
################################################################################
# local mcc - oracle
################################################################################
local.mcc.oracle.jdbc.driver=oracle.jdbc.driver.OracleDriver
local.mcc.oracle.jdbc.url=jdbc:oracle:thin:@192.168.120.216:1522:XE
local.mcc.oracle.jdbc.username=IIAPKG
local.mcc.oracle.jdbc.password=elink
################################################################################
# local mcu - oracle
################################################################################
local.mcu.oracle.jdbc.driver=oracle.jdbc.driver.OracleDriver
local.mcu.oracle.jdbc.url=jdbc:oracle:thin:@192.168.120.216:1522:XE
local.mcu.oracle.jdbc.username=IIUPKG
local.mcu.oracle.jdbc.password=elink
################################################################################
# local fep - oracle
################################################################################
local.fep.oracle.jdbc.driver=oracle.jdbc.driver.OracleDriver
local.fep.oracle.jdbc.url=jdbc:oracle:thin:@192.168.120.216:1522:XE
local.fep.oracle.jdbc.username=IIBPKG
local.fep.oracle.jdbc.password=elink
################################################################################
# local eai - oracle
################################################################################
local.eai.oracle.jdbc.driver=oracle.jdbc.driver.OracleDriver
local.eai.oracle.jdbc.url=jdbc:oracle:thin:@192.168.120.216:1522:XE
local.eai.oracle.jdbc.username=IICPKG
local.eai.oracle.jdbc.password=elink
################################################################################
# dev mcc - oracle
################################################################################
dev.mcc.oracle.jdbc.driver=oracle.jdbc.OracleDriver
dev.mcc.oracle.jdbc.url=jdbc:oracle:thin:@172.16.141.11:11521:DMCCDB
dev.mcc.oracle.jdbc.username=IIAPKG
dev.mcc.oracle.jdbc.password=iiapkg2021!
################################################################################
# dev mcu - oracle
################################################################################
dev.mcu.oracle.jdbc.driver=oracle.jdbc.OracleDriver
dev.mcu.oracle.jdbc.url=jdbc:oracle:thin:@172.16.141.21:11521:DMCUDB
dev.mcu.oracle.jdbc.username=IIAPKG
dev.mcu.oracle.jdbc.password=iiapkg2021!
################################################################################
# dev fep - oracle
################################################################################
dev.fep.oracle.jdbc.driver=oracle.jdbc.OracleDriver
dev.fep.oracle.jdbc.url=jdbc:oracle:thin:@172.16.142.11:11521:DFEPDB
dev.fep.oracle.jdbc.username=IIBPKG
dev.fep.oracle.jdbc.password=iibpkg2021!
################################################################################
# dev eai - oracle
################################################################################
dev.eai.oracle.jdbc.driver=oracle.jdbc.OracleDriver
dev.eai.oracle.jdbc.url=jdbc:oracle:thin:@172.16.141.31:11521:DEAIDB
dev.eai.oracle.jdbc.username=IICPKG
dev.eai.oracle.jdbc.password=iicpkg2021!
################################################################################
# eai local - db2
################################################################################
localold.eai.db2.jdbc.driver=com.ibm.db2.jcc.DB2Driver
localold.eai.db2.jdbc.url=jdbc:db2://192.168.241.96:50000/DSEAIW
localold.eai.db2.jdbc.username=eai000
localold.eai.db2.jdbc.password=Eoss01!!
################################################################################
# eai local - mariadb
################################################################################
local.eai.mariadb.jdbc.driver=com.mysql.jdbc.Driver
local.eai.mariadb.jdbc.url=jdbc:mysql://192.168.8.21:4306/eai?useSSL=false&characterEncoding=euckr
local.eai.mariadb.jdbc.username=eai
Binary file not shown.
+6
View File
@@ -0,0 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
networkTimeout=10000
Vendored
+234
View File
@@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+89
View File
@@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+9
View File
@@ -0,0 +1,9 @@
# eLink 온라인 전문 및 변환 관련 모듈
전문 레이아웃 및 변환 관련 모듈
### nexus password
대상파일 : gradle.properties
```ini
eactiveRepositoryUsername={사용자명}
eactiveRepositoryPassword={비밀번호}
```
+7
View File
@@ -0,0 +1,7 @@
rootProject.name = 'elink-online-transformer'
include 'elink-online-core'
include 'elink-online-core-jpa'
project (':elink-online-core').projectDir = new File(settingsDir, "../elink-online-core")
project (':elink-online-core-jpa').projectDir = new File(settingsDir, "../elink-online-core-jpa")
@@ -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);
}
}
}

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